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_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
#BASIC256
BASIC256
subroutine opener (filename$) if exists(filename$) then print filename$; " exists" else print filename$; " does not exists" end if end subroutine   call opener ("input.txt") call opener ("\input.txt") call opener ("docs\nul") call opener ("\docs\nul") call opener ("empty.kbs") call opener ("`Abdu'l-Bahá.txt")) 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
#Batch_File
Batch File
if exist input.txt echo The following file called input.txt exists. if exist \input.txt echo The following file called \input.txt exists. if exist docs echo The following directory called docs exists. if exist \docs\ echo The following directory called \docs\ exists.
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.2B.2B
C++
  #include <windows.h> #include <ctime> #include <string> #include <iostream>   const int BMP_SIZE = 600;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } void saveBitmap( std::string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap ); DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];   ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class chaos { public: void start() { POINT org; fillPts(); initialPoint( org ); initColors(); int cnt = 0, i; bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear( 255 );   while( cnt++ < 1000000 ) { switch( rand() % 6 ) { case 0: case 3: i = 0; break; case 1: case 5: i = 1; break; case 2: case 4: i = 2; } setPoint( org, myPoints[i], i ); } // --- edit this path --- // bmp.saveBitmap( "F:/st.bmp" ); } private: void setPoint( POINT &o, POINT v, int i ) { POINT z; o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1; SetPixel( bmp.getDC(), o.x, o.y, colors[i] ); } void fillPts() { int a = BMP_SIZE - 1; myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0; myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a; } void initialPoint( POINT& p ) { p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 ); } void initColors() { colors[0] = RGB( 255, 0, 0 ); colors[1] = RGB( 0, 255, 0 ); colors[2] = RGB( 0, 0, 255 ); }   myBitmap bmp; POINT myPoints[3]; COLORREF colors[3]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chaos c; c.start(); 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.
#Common_Lisp
Common Lisp
  (ql:quickload '(:usocket :simple-actors :bordeaux-threads))   (defpackage :chat-server (:use :common-lisp :usocket :simple-actors :bordeaux-threads) (:export :accept-connections))   (in-package :chat-server)   (defvar *whitespace* '(#\Space #\Tab #\Page #\Vt #\Newline #\Return))   (defun send-message (users from-user message) (loop for (nil . actor) in users do (send actor :message from-user message)))   (defun socket-format (socket format-control &rest format-arguments) (apply #'format (socket-stream socket) format-control format-arguments) (finish-output (socket-stream socket)))   (defvar *log* *standard-output*)   (defmacro log-errors (&body body) `(handler-case (progn ,@body) (t (err) (format *log* "Error: ~a" err))))   (defparameter *user-manager* (let ((users nil)) (actor (action &rest args) (format *log* "Handling message ~s~%" (cons action args)) (ecase action (:newuser (destructuring-bind (username session-actor) args (cond ((assoc username users :test #'equalp) (send session-actor :rejected (format nil "Username ~a is already taken. Send /NICK new-nick with a valid name to enter the chat~%" username))) ((equalp username "Server") (send session-actor :rejected (format nil "Server is not a valid username. Send /NICK new-nick with a valid name to enter the chat~%"))) (t (send-message users "Server" (format nil "~a has joined the chat." username)) (send session-actor :accepted (format nil "Welcome to the Rosetta Code chat server in Common Lisp. ~a users connected.~%" (length users))) (pushnew (cons username session-actor) users  :key #'car  :test #'equalp))))) (:who (destructuring-bind (username) args (let ((actor (cdr (assoc username users :test #'equalp)))) (send actor :message "Server" "Users connected right now:") (loop for (user . nil) in users do (send actor :message "Server" user))))) (:message (apply #'send-message users args)) (:dropuser (destructuring-bind (username) args (let ((user-actor (cdr (assoc username users :test #'equalp)))) (send user-actor :close) (send user-actor 'stop)) (setf users (remove username users :key #'car :test #'equalp)) (send-message users "Server" (format nil "~a has left." username))))))))   (defmacro drop-connection-on-error (&body body) `(handler-case (progn ,@body) (t (err) (format *log* "Error: ~a; Closing connection" err) (send self :close) (send self 'stop) (send *user-manager* :dropuser username))))   (defun parse-command (message) (let* ((space-at (position #\Space message)) (after-space (and space-at (position-if (lambda (ch) (not (char= ch #\Space))) message :start (1+ space-at))))) (values (subseq message 0 space-at) (and after-space (string-trim *whitespace* (subseq message after-space))))))   (defun help (socket) (socket-format socket "/QUIT to quit, /WHO to list users.~%"))   (defun make-user (username socket) (let* ((state :unregistered) (actor (actor (message &rest args) (drop-connection-on-error (ecase message (:register (send *user-manager* :newuser username self)) (:accepted (destructuring-bind (message) args (write-string message (socket-stream socket)) (finish-output (socket-stream socket)) (setf state :registered))) (:rejected (destructuring-bind (message) args (write-string message (socket-stream socket)) (finish-output (socket-stream socket)) (setf state :unregistered))) (:user-typed (destructuring-bind (message) args (when (> (length message) 0) (if (char= (aref message 0) #\/) (multiple-value-bind (cmd arg) (parse-command message) (cond ((equalp cmd "/nick") (ecase state (:unregistered (setf username arg) (send *user-manager* :newuser username self)) (:registered (socket-format socket "Can't change your name after successfully registering~%")))) ((equalp cmd "/help") (help socket)) ((equalp cmd "/who") (send *user-manager* :who username)) ((equalp cmd "/quit") (socket-format socket "Goodbye.~%") (send *user-manager* :dropuser username)) (t (socket-format socket "Unknown command~%")))) (send *user-manager* :message username message))))) (:message (destructuring-bind (from-user message) args (socket-format socket "<~a> ~a~%" from-user message))) (:close (log-errors (close (socket-stream socket))))))))) (bt:make-thread (lambda () (handler-case (loop for line = (read-line (socket-stream socket) nil :eof) do (if (eq line :eof) (send *user-manager* :dropuser username) (send actor :user-typed (remove #\Return line)))) (t () (send *user-manager* :dropuser username))))    :name "Reader thread") actor))     (defun initialize-user (socket) (bt:make-thread (lambda () (format *log* "Handling new connection ~s" socket) (log-errors (loop do (socket-format socket "Your name: ") (let ((name (string-trim *whitespace* (read-line (socket-stream socket))))) (format *log* "Registering user ~a" name) (cond ((equalp name "Server") (socket-format socket "Server is not a valid username.~%")) (t (send *user-manager*  :newuser name (make-user name socket)) (return)))))))  :name "INITIALIZE-USER"))     (defun accept-connections () (let ((accepting-socket (socket-listen "0.0.0.0" 7070))) (loop for new-connection = (socket-accept accepting-socket) do (initialize-user new-connection))))   (make-thread #'accept-connections)  
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.
#Julia
Julia
  using AbstractAlgebra # implements arbitrary precision rationals   tanplus(x,y) = (x + y) / (1 - x * y)   function taneval(coef, frac) if coef == 0 return 0 elseif coef < 0 return -taneval(-coef, frac) elseif isodd(coef) return tanplus(frac, taneval(coef - 1, frac)) else x = taneval(div(coef, 2), frac) return tanplus(x, x) end end   taneval(tup::Tuple) = taneval(tup[1], tup[2])   tans(v::Vector{Tuple{BigInt, Rational{BigInt}}}) = foldl(tanplus, map(taneval, v), init=0)   const testmats = Dict{Vector{Tuple{BigInt, Rational{BigInt}}}, Bool}([ ([(1, 1//2), (1, 1//3)], true), ([(2, 1//3), (1, 1//7)], true), ([(12, 1//18), (8, 1//57), (-5, 1//239)], true), ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12943)], true), ([(88, 1//172), (51, 1//239), (32, 1//682), (44, 1//5357), (68, 1//12944)], false)])     function runtestmats() println("Testing matrices:") for (k, m) in testmats ans = tans(k) println((ans == 1) == m ? "Verified as $m: " : "Not Verified as $m: ", "tan $k = $ans") end end   runtestmats()  
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.
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE   class BigRational : Comparable<BigRational> {   val num: BigInteger val denom: BigInteger   constructor(n: BigInteger, d: BigInteger) { require(d != bigZero) var nn = n var dd = d if (nn == bigZero) { dd = bigOne } else if (dd < bigZero) { nn = -nn dd = -dd } val g = nn.gcd(dd) if (g > bigOne) { nn /= g dd /= g } num = nn denom = dd }   constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d))   operator fun plus(other: BigRational) = BigRational(num * other.denom + denom * other.num, other.denom * denom)   operator fun unaryMinus() = BigRational(-num, denom)   operator fun minus(other: BigRational) = this + (-other)   operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom)   fun inverse(): BigRational { require(num != bigZero) return BigRational(denom, num) }   operator fun div(other: BigRational) = this * other.inverse()   override fun compareTo(other: BigRational): Int { val diff = this - other return when { diff.num < bigZero -> -1 diff.num > bigZero -> +1 else -> 0 } }   override fun equals(other: Any?): Boolean { if (other == null || other !is BigRational) return false return this.compareTo(other) == 0 }   override fun toString() = if (denom == bigOne) "$num" else "$num/$denom"   companion object { val ZERO = BigRational(bigZero, bigOne) val ONE = BigRational(bigOne, bigOne) } }   /** represents a term of the form: c * atan(n / d) */ class Term(val c: Long, val n: Long, val d: Long) {   override fun toString() = when { c == 1L -> " + " c == -1L -> " - " c < 0L -> " - ${-c}*" else -> " + $c*" } + "atan($n/$d)" }   val one = BigRational.ONE   fun tanSum(terms: List<Term>): BigRational { if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d)) val half = terms.size / 2 val a = tanSum(terms.take(half)) val b = tanSum(terms.drop(half)) return (a + b) / (one - (a * b)) }   fun tanEval(c: Long, f: BigRational): BigRational { if (c == 1L) return f if (c < 0L) return -tanEval(-c, f) val ca = c / 2 val cb = c - ca val a = tanEval(ca, f) val b = tanEval(cb, f) return (a + b) / (one - (a * b)) }   fun main(args: Array<String>) { val termsList = listOf( listOf(Term(1, 1, 2), Term(1, 1, 3)), listOf(Term(2, 1, 3), Term(1, 1, 7)), listOf(Term(4, 1, 5), Term(-1, 1, 239)), listOf(Term(5, 1, 7), Term(2, 3, 79)), listOf(Term(5, 29, 278), Term(7, 3, 79)), listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)), listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)), listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)), listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)), listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)), listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)), listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)), listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)), listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)), listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)), listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)), listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944)) )   for (terms in termsList) { val f = String.format("%-5s << 1 == tan(", tanSum(terms) == one) print(f) print(terms[0].toString().drop(3)) for (i in 1 until terms.size) print(terms[i]) println(")") } }
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.
#Arturo
Arturo
print to :integer first "a" print to :integer `a` print to :char 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.
#AutoHotkey
AutoHotkey
MsgBox % Chr(97) MsgBox % Asc("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.
#Haskell
Haskell
module Cholesky (Arr, cholesky) where   import Data.Array.IArray import Data.Array.MArray import Data.Array.Unboxed import Data.Array.ST   type Idx = (Int,Int) type Arr = UArray Idx Double   -- Return the (i,j) element of the lower triangular matrix. (We assume the -- lower array bound is (0,0).) get :: Arr -> Arr -> Idx -> Double get a l (i,j) | i == j = sqrt $ a!(j,j) - dot | i > j = (a!(i,j) - dot) / l!(j,j) | otherwise = 0 where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]]   -- Return the lower triangular matrix of a Cholesky decomposition. We assume -- the input is a real, symmetric, positive-definite matrix, with lower array -- bounds of (0,0). cholesky :: Arr -> Arr cholesky a = let n = maxBnd a in runSTUArray $ do l <- thaw a mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]] return l where maxBnd = fst . snd . bounds update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)
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
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.List as L (filter, groupBy, head, length, sortOn) import Data.Map.Strict as M (Map, fromList, keys, lookup) import Data.Text as T (Text, splitOn, words) import Data.Maybe (fromJust) import Data.Ord (comparing) import Data.Function (on) import Data.Tuple (swap) import Data.Bool (bool)   data DatePart = Month | Day   type M = Text   type D = Text   main :: IO () main = print $ -- The month with only one remaining day, -- -- (A's month contains only one remaining day) -- (3 :: A "Then I also know") uniquePairing Month $ -- among the days with unique months, -- -- (B's day is paired with only one remaining month) -- (2 :: B "I know now") uniquePairing Day $ -- excluding months with unique days, -- -- (A's month is not among those with unique days) -- (1 :: A "I know that Bernard does not know") monthsWithUniqueDays False $ -- from the given month-day pairs: -- -- (0 :: Cheryl's list) (\(x:y:_) -> (x, y)) . T.words <$> splitOn ", " "May 15, May 16, May 19, June 17, June 18, \ \July 14, July 16, Aug 14, Aug 15, Aug 17"   ----------------------QUERY FUNCTIONS---------------------- monthsWithUniqueDays :: Bool -> [(M, D)] -> [(M, D)] monthsWithUniqueDays bln xs = let months = fst <$> uniquePairing Day xs in L.filter (bool not id bln . (`elem` months) . fst) xs   uniquePairing :: DatePart -> [(M, D)] -> [(M, D)] uniquePairing dp xs = let f = case dp of Month -> fst Day -> snd in (\md -> let dct = f md uniques = L.filter ((1 ==) . L.length . fromJust . flip M.lookup dct) (keys dct) in L.filter ((`elem` uniques) . f) xs) ((((,) . mapFromPairs) <*> mapFromPairs . fmap swap) xs)   mapFromPairs :: [(M, D)] -> Map Text [Text] mapFromPairs xs = M.fromList $ ((,) . fst . L.head) <*> fmap snd <$> L.groupBy (on (==) fst) (L.sortOn fst xs)
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.
#Phix
Phix
-- demo\rosetta\checkpoint_synchronisation.exw without js -- task_xxx(), get_key() constant NPARTS = 3 integer workers = 0 sequence waiters = {} bool terminate = false procedure checkpoint(integer task_id) if length(waiters)+1=NPARTS or terminate then printf(1,"checkpoint\n") for i=1 to length(waiters) do task_schedule(waiters[i],1) end for waiters = {} else waiters &= task_id task_suspend(task_id) task_yield() end if end procedure procedure worker(string name) printf(1,"worker %s running\n",{name}) while not terminate do printf(1,"worker %s begins part\n",{name}) task_delay(rnd()) printf(1,"worker %s completes part\n",{name}) checkpoint(task_self()) if find(task_self(),waiters) then ?9/0 end if if terminate or rnd()>0.95 then exit end if task_delay(rnd()) end while printf(1,"worker %s leaves\n",{name}) workers -= 1 end procedure string name = "A" while get_key()!=#1B do -- (key escape to shut down) if workers<NPARTS then integer task_id = task_create(routine_id("worker"),{name}) task_schedule(task_id,1) name[1] += 1 workers += 1 end if task_yield() end while printf(1,"escape keyed\n") terminate = true while workers>0 do task_yield() end while {} = wait_key()
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
#Java
Java
List arrayList = new ArrayList(); arrayList.add(new Integer(0)); // alternative with primitive autoboxed to an Integer object automatically arrayList.add(0);   //other features of ArrayList //define the type in the arraylist, you can substitute a proprietary class in the "<>" List<Integer> myarrlist = new ArrayList<Integer>();   //add several values to the arraylist to be summed later int sum; for(int i = 0; i < 10; i++) { myarrlist.add(i); }
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
#Octave
Octave
nchoosek([0:4], 3)
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.
#RLaB
RLaB
  if (x==1) { // do something }  
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}}} .
#Factor
Factor
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
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}}} .
#Forth
Forth
: egcd ( a b -- a b ) dup 0= IF 2drop 1 0 ELSE dup -rot /mod \ -- b r=a%b q=a/b -rot recurse \ -- q (s,t) = egcd(b, r) >r swap r@ * - r> swap \ -- t (s - q*t) THEN ;   : egcd>gcd ( a b x y -- n ) \ calculate gcd from egcd rot * -rot * + ;   : mod-inv ( a m -- a' ) \ modular inverse with coprime check 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ;   : array-product ( adr count -- n ) 1 -rot cells bounds ?DO i @ * cell +LOOP ;   : crt-from-array ( adr1 adr2 count -- n ) 2dup array-product locals| M count m[] a[] | 0 \ result count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ;   create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot   : crt ( .... n -- n ) \ takes pairs of "n (mod m)" from stack. 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[Chowla] Chowla[0 | 1] := 0 Chowla[n_] := DivisorSigma[1, n] - 1 - n Table[{i, Chowla[i]}, {i, 37}] // Grid PrintTemporary[Dynamic[n]]; i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 100, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 1000, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 10000, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 100000, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 1000000, 2}]; i i = 1; Do[If[Chowla[n] == 0, i++], {n, 3, 10000000, 2}]; i Reap[Do[If[Chowla[n] == n - 1, Sow[n]], {n, 1, 35 10^6}]][[2, 1]]
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.
#Nim
Nim
import strformat import strutils   func chowla(n: uint64): uint64 = var sum = 0u64 var i = 2u64 var j: uint64 while i * i <= n: if n mod i == 0: j = n div i sum += i if i != j: sum += j inc i sum   for n in 1u64..37: echo &"chowla({n}) = {chowla(n)}"   var count = 0 var power = 100u64 for n in 2u64..10_000_000: if chowla(n) == 0: inc count if n mod power == 0: echo &"There are {insertSep($count, ','):>7} primes < {insertSep($power, ','):>10}" power *= 10   count = 0 const limit = 350_000_000u64 var k = 2u64 var kk = 3u64 var p: uint64 while true: p = k * kk if p > limit: break if chowla(p) == p - 1: echo &"{insertSep($p, ','):>10} is a perfect number" inc count k = kk + 1 kk += k echo &"There are {count} perfect numbers < {insertSep($limit, ',')}"
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.
#Racket
Racket
#lang racket   (define zero (λ (f) (λ (x) x))) (define zero* (const identity)) ; zero renamed   (define one (λ (f) f)) (define one* identity) ; one renamed   (define succ (λ (n) (λ (f) (λ (x) (f ((n f) x)))))) (define succ* (λ (n) (λ (f) (λ (x) ((n f) (f x)))))) ; different impl   (define add (λ (n) (λ (m) (λ (f) (λ (x) ((m f) ((n f) x))))))) (define add* (λ (n) (n succ)))   (define succ** (add one))   (define mult (λ (n) (λ (m) (λ (f) (m (n f)))))) (define mult* (λ (n) (λ (m) ((m (add n)) zero))))   (define expt (λ (n) (λ (m) (m n)))) (define expt* (λ (n) (λ (m) ((m (mult n)) one))))   (define (nat->church n) (cond [(zero? n) zero] [else (succ (nat->church (sub1 n)))]))   (define (church->nat n) ((n add1) 0))   (define three (nat->church 3)) (define four (nat->church 4))   (church->nat ((add three) four)) (church->nat ((mult three) four)) (church->nat ((expt three) four)) (church->nat ((expt four) three))
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.
#Raku
Raku
constant $zero = sub (Code $f) { sub ( $x) { $x }}   constant $succ = sub (Code $n) { sub (Code $f) { sub ( $x) { $f($n($f)($x)) }}}   constant $add = sub (Code $n) { sub (Code $m) { sub (Code $f) { sub ( $x) { $m($f)($n($f)($x)) }}}}   constant $mult = sub (Code $n) { sub (Code $m) { sub (Code $f) { sub ( $x) { $m($n($f))($x) }}}}   constant $power = sub (Code $b) { sub (Code $e) { $e($b) }}   sub to_int (Code $f) { sub countup (Int $i) { $i + 1 } return $f(&countup).(0) }   sub from_int (Int $x) { multi sub countdown ( 0) { $zero } multi sub countdown (Int $i) { $succ( countdown($i - 1) ) } return countdown($x); }   constant $three = $succ($succ($succ($zero))); constant $four = from_int(4);   say map &to_int, $add( $three )( $four ), $mult( $three )( $four ), $power( $four )( $three ), $power( $three )( $four ), ;
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.
#Icon_and_Unicon
Icon and Unicon
class Example (x) # 'x' is a field in class   # method definition method double () return 2 * x end   # 'initially' block is called on instance construction initially (x) if /x # if x is null (not given), then set field to 0 then self.x := 0 else self.x := x end   procedure main () x1 := Example () # new instance with default value of x x2 := Example (2) # new instance with given value of x write (x1.x) write (x2.x) write (x2.double ()) # call a method end
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
nearestPair[data_] := Block[{pos, dist = N[Outer[EuclideanDistance, data, data, 1]]}, pos = Position[dist, Min[DeleteCases[Flatten[dist], 0.]]]; data[[pos[[1]]]]]
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
#Rust
Rust
fn main() { let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); println!("7th val: {}", fs[7]()); }
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
#Scala
Scala
val closures=for(i <- 0 to 9) yield (()=>i*i) 0 to 8 foreach (i=> println(closures(i)())) println("---\n"+closures(7)())
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
#Groovy
Groovy
class Circles { private static class Point { private final double x, y   Point(Double x, Double y) { this.x = x this.y = y }   double distanceFrom(Point other) { double dx = x - other.x double dy = y - other.y return Math.sqrt(dx * dx + dy * dy) }   @Override boolean equals(Object other) { //if (this == other) return true if (other == null || getClass() != other.getClass()) return false Point point = (Point) other return x == point.x && y == point.y }   @Override String toString() { return String.format("(%.4f, %.4f)", x, y) } }   private static Point[] findCircles(Point p1, Point p2, double r) { if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative") if (r == 0.0.toDouble() && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn") if (r == 0.0.toDouble()) return [p1, p1] if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn") double distance = p1.distanceFrom(p2) double diameter = 2.0 * r if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle") Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0) if (distance == diameter) return [center, center] double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0) double dx = (p2.x - p1.x) * mirrorDistance / distance double dy = (p2.y - p1.y) * mirrorDistance / distance return [ new Point(center.x - dy, center.y + dx), new Point(center.x + dy, center.y - dx) ] }   static void main(String[] args) { Point[] p = [ new Point(0.1234, 0.9876), new Point(0.8765, 0.2345), new Point(0.0000, 2.0000), new Point(0.0000, 0.0000) ] Point[][] points = [ [p[0], p[1]], [p[2], p[3]], [p[0], p[0]], [p[0], p[1]], [p[0], p[0]], ] double[] radii = [2.0, 1.0, 2.0, 0.5, 0.0] for (int i = 0; i < radii.length; ++i) { Point p1 = points[i][0] Point p2 = points[i][1] double r = radii[i] printf("For points %s and %s with radius %f\n", p1, p2, r) try { Point[] circles = findCircles(p1, p2, r) Point c1 = circles[0] Point c2 = circles[1] if (Objects.equals(c1, c2)) { printf("there is just one circle with center at %s\n", c1) } else { printf("there are two circles with centers at %s and %s\n", c1, c2) } } catch (IllegalArgumentException ex) { println(ex.getMessage()) } 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).
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲乙丙丁戊己庚辛壬癸") branchCh = []rune("子丑寅卯辰巳午未申酉戌亥") )   func cz(yr int) (animal, yinYang, element, stemBranch string, cycleYear int) { yr -= 4 stem := yr % 10 branch := yr % 12 return animalString[branch], stemYYString[stem%2], elementString[stem/2], string([]rune{stemCh[stem], branchCh[branch]}), yr%60 + 1 }   func main() { for _, yr := range []int{1935, 1938, 1968, 1972, 1976} { a, yy, e, sb, cy := cz(yr) fmt.Printf("%d: %s %s, %s, Cycle year %d %s\n", yr, e, a, yy, cy, sb) } }
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
#BBC_BASIC
BBC BASIC
test% = OPENIN("input.txt") IF test% THEN CLOSE #test% PRINT "File input.txt exists" ENDIF   test% = OPENIN("\input.txt") IF test% THEN CLOSE #test% PRINT "File \input.txt exists" ENDIF   test% = OPENIN("docs\NUL") IF test% THEN CLOSE #test% PRINT "Directory docs exists" ENDIF   test% = OPENIN("\docs\NUL") IF test% THEN CLOSE #test% PRINT "Directory \docs exists" ENDIF
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
#BQN
BQN
fname ← ⊑args •Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname
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
#Common_Lisp
Common Lisp
(defpackage #:chaos (:use #:cl #:opticl))   (in-package #:chaos)   (defparameter *image-size* 600) (defparameter *margin* 50) (defparameter *edge-size* (- *image-size* *margin* *margin*)) (defparameter *iterations* 1000000)   (defun chaos () (let ((image (make-8-bit-rgb-image *image-size* *image-size* :initial-element 255)) (a (list (- *image-size* *margin*) *margin*)) (b (list (- *image-size* *margin*) (- *image-size* *margin*))) (c (list (- *image-size* *margin* (round (* (tan (/ pi 3)) *edge-size*) 2)) (round *image-size* 2))) (point (list (+ (random *edge-size*) *margin*) (+ (random *edge-size*) *margin*)))) (dotimes (i *iterations*) (let ((ref (ecase (random 3) (0 a) (1 b) (2 c)))) (setf point (list (round (+ (first point) (first ref)) 2) (round (+ (second point) (second ref)) 2)))) (setf (pixel image (first point) (second point)) (values 255 0 0))) (write-png-file "chaos.png" image)))
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.
#Erlang
Erlang
  -module(chat).   -export([start/0, start/1]).   -record(client, {name=none, socket=none}).   start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket).   % main loop for message dispatcher server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients).   % accepts connections then spawns the client handler accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket).   % when client is first connect send prompt for user name connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end.   % main client loop that listens for data client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end.   % utility function that listens for data on a socket listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Tan[ArcTan[1/2] + ArcTan[1/3]] == 1 Tan[2 ArcTan[1/3] + ArcTan[1/7]] == 1 Tan[4 ArcTan[1/5] - ArcTan[1/239]] == 1 Tan[5 ArcTan[1/7] + 2 ArcTan[3/79]] == 1 Tan[5 ArcTan[29/278] + 7 ArcTan[3/79]] == 1 Tan[ArcTan[1/2] + ArcTan[1/5] + ArcTan[1/8]] == 1 Tan[4 ArcTan[1/5] - ArcTan[1/70] + ArcTan[1/99]] == 1 Tan[5 ArcTan[1/7] + 4 ArcTan[1/53] + 2 ArcTan[1/4443]] == 1 Tan[6 ArcTan[1/8] + 2 ArcTan[1/57] + ArcTan[1/239]] == 1 Tan[8 ArcTan[1/10] - ArcTan[1/239] - 4 ArcTan[1/515]] == 1 Tan[12 ArcTan[1/18] + 8 ArcTan[1/57] - 5 ArcTan[1/239]] == 1 Tan[16 ArcTan[1/21] + 3 ArcTan[1/239] + 4 ArcTan[3/1042]] == 1 Tan[22 ArcTan[1/28] + 2 ArcTan[1/443] - 5 ArcTan[1/1393] - 10 ArcTan[1/11018]] == 1 Tan[22 ArcTan[1/38] + 17 ArcTan[7/601] + 10 ArcTan[7/8149]] == 1 Tan[44 ArcTan[1/57] + 7 ArcTan[1/239] - 12 ArcTan[1/682] + 24 ArcTan[1/12943]] == 1 Tan[88 ArcTan[1/172] + 51 ArcTan[1/239] + 32 ArcTan[1/682] + 44 ArcTan[1/5357] + 68 ArcTan[1/12943]] == 1 Tan[88 ArcTan[1/172] + 51 ArcTan[1/239] + 32 ArcTan[1/682] + 44 ArcTan[1/5357] + 68 ArcTan[1/12944]] == 1
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.
#Maxima
Maxima
trigexpand:true$ is(tan(atan(1/2)+atan(1/3))=1); is(tan(2*atan(1/3)+atan(1/7))=1); is(tan(4*atan(1/5)-atan(1/239))=1); is(tan(5*atan(1/7)+2*atan(3/79))=1); is(tan(5*atan(29/278)+7*atan(3/79))=1); is(tan(atan(1/2)+atan(1/5)+atan(1/8))=1); is(tan(4*atan(1/5)-atan(1/70)+atan(1/99))=1); is(tan(5*atan(1/7)+4*atan(1/53)+2*atan(1/4443))=1); is(tan(6*atan(1/8)+2*atan(1/57)+atan(1/239))=1); is(tan(8*atan(1/10)-atan(1/239)-4*atan(1/515))=1); is(tan(12*atan(1/18)+8*atan(1/57)-5*atan(1/239))=1); is(tan(16*atan(1/21)+3*atan(1/239)+4*atan(3/1042))=1); is(tan(22*atan(1/28)+2*atan(1/443)-5*atan(1/1393)-10*atan(1/11018))=1); is(tan(22*atan(1/38)+17*atan(7/601)+10*atan(7/8149))=1); is(tan(44*atan(1/57)+7*atan(1/239)-12*atan(1/682)+24*atan(1/12943))=1); is(tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12943))=1); is(tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12944))=1);
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.
#AWK
AWK
function ord(c) { return chmap[c] } BEGIN { for(i=0; i < 256; i++) { chmap[sprintf("%c", i)] = i } print ord("a"), ord("b") printf "%c %c\n", 97, 98 s = sprintf("%c%c", 97, 98) print s }
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.
#Icon_and_Unicon
Icon and Unicon
procedure cholesky (array) result := make_square_array (*array) every (i := 1 to *array) do { every (k := 1 to i) do { sum := 0 every (j := 1 to (k-1)) do { sum +:= result[i][j] * result[k][j] } if (i = k) then result[i][k] := sqrt(array[i][i] - sum) else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum) } } return result end   procedure make_square_array (n) result := [] every (1 to n) do push (result, list(n, 0)) return result end   procedure print_array (array) every (row := !array) do { every writes (!row || " ") write () } end   procedure do_cholesky (array) write ("Input:") print_array (array) result := cholesky (array) write ("Result:") print_array (result) end   procedure main () do_cholesky ([[25,15,-5],[15,18,0],[-5,0,11]]) do_cholesky ([[18,22,54,42],[22,70,86,62],[54,86,174,134],[42,62,134,106]]) 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
#J
J
Dates=: <;._2 noun define 15 May 16 May 19 May 17 June 18 June 14 July 16 July 14 August 15 August 17 August )   getDayMonth=: |:@:(' '&splitstring&>) NB. retrieve lists of days and months from dates keep=: adverb def '] #~ u' NB. apply mask to filter dates   monthsWithUniqueDay=: {./. #~ (1=#)/. NB. list months that have a unique day isMonthWithoutUniqueDay=: (] -.@e. monthsWithUniqueDay)/@getDayMonth NB. mask of dates with a month that doesn't have a unique day   uniqueDayInMonth=: ~.@[ #~ (1=#)/. NB. list of days that are unique to 1 month isUniqueDayInMonth=: ([ e. uniqueDayInMonth)/@getDayMonth NB. mask of dates with a day that is unique to 1 month   uniqueMonth=: ~.@] #~ (1=#)/.~ NB. list of months with 1 unique day isUniqueMonth=: (] e. uniqueMonth)/@getDayMonth NB. mask of dates with a month that has 1 unique 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.
#PicoLisp
PicoLisp
(de checkpoints (Projects Workers) (for P Projects (prinl "Starting project number " P ":") (for (Staff (mapcar '((I) (worker (format I) (rand 2 5))) # Create staff of workers (range 1 Workers) ) Staff # While still busy (filter worker Staff) ) ) # Remove finished workers (prinl "Project number " P " is done.") ) )   (de worker (ID Steps) (co ID (prinl "Worker " ID " has " Steps " steps to do") (for N Steps (yield ID) (prinl "Worker " ID " step " N) ) NIL ) )
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.
#PureBasic
PureBasic
#MaxWorktime=8000 ; "Workday" in msec   ; Structure that each thread uses Structure MyIO ThreadID.i Semaphore_Joining.i Semaphore_Release.i Semaphore_Deliver.i Semaphore_Leaving.i EndStructure   ; Array of used threads Global Dim Comm.MyIO(0)   ; Master loop synchronizing the threads via semaphores Procedure CheckPoint() Protected i, j, maxthreads=ArraySize(Comm()) Protected Worker_count, Deliver_count Repeat For i=1 To maxthreads With Comm(i) If TrySemaphore(\Semaphore_Leaving) Worker_count-1 ElseIf TrySemaphore(\Semaphore_Deliver) Deliver_count+1 If Deliver_count=Worker_count PrintN("All Workers reported in, starting next task.") Deliver_count=0 For j=1 To maxthreads SignalSemaphore(Comm(j)\Semaphore_Release) Next j EndIf ElseIf TrySemaphore(\Semaphore_Joining) PrintN("A new Worker joined the force.") Worker_count+1: SignalSemaphore(\Semaphore_Release) ElseIf Worker_count=0 ProcedureReturn EndIf Next i EndWith ForEver StartAll=0 EndProcedure   ; A worker thread, all orchestrated by the Checkpoint() routine Procedure Worker(ID) Protected EndTime=ElapsedMilliseconds()+#MaxWorktime, n With Comm(ID) SignalSemaphore(\Semaphore_Joining) Repeat Repeat ; Use a non-blocking semaphore check to avoid dead-locking at shutdown. If ElapsedMilliseconds()>EndTime SignalSemaphore(\Semaphore_Leaving) PrintN("Thread #"+Str(ID)+" is done.") ProcedureReturn EndIf Delay(1) Until TrySemaphore(\Semaphore_Release) n=Random(1000) PrintN("Thread #"+Str(ID)+" will work for "+Str(n)+" msec.") Delay(n): PrintN("Thread #"+Str(ID)+" delivering") SignalSemaphore(\Semaphore_Deliver) ForEver EndWith EndProcedure   ; User IO & init If OpenConsole() Define i, j Repeat Print("Enter number of workers to use [2-2000]: ") j=Val(Input()) Until j>=2 And j<=2000 ReDim Comm(j) For i=1 To j With Comm(i) \Semaphore_Release =CreateSemaphore() \Semaphore_Joining =CreateSemaphore() \Semaphore_Deliver =CreateSemaphore() \Semaphore_Leaving =CreateSemaphore() \ThreadID = CreateThread(@Worker(),i) EndWith Next PrintN("Work started, "+Str(j)+" workers has been called.") CheckPoint() Print("Press ENTER to exit"): Input() EndIf
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
#JavaScript
JavaScript
var array = []; array.push('abc'); array.push(123); array.push(new MyClass); console.log( array[2] );
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
#OpenEdge.2FProgress
OpenEdge/Progress
  define variable r as integer no-undo extent 3. define variable m as integer no-undo initial 5. define variable n as integer no-undo initial 3. define variable max_n as integer no-undo.   max_n = m - n.   function combinations returns logical (input pos as integer, input val as integer): define variable i as integer no-undo. do i = val to max_n: r[pos] = pos + i. if pos lt n then combinations(pos + 1, i). else message r[1] - 1 r[2] - 1 r[3] - 1. end. end function.   combinations(1, 0).  
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.
#Ruby
Ruby
' Boolean Evaluations ' ' > Greater Than ' < Less Than ' >= Greater Than Or Equal To ' <= Less Than Or Equal To ' = Equal to   x = 0   if x = 0 then print "Zero"   ' -------------------------- ' if/then/else if x = 0 then print "Zero" else print "Nonzero" end if   ' -------------------------- ' not if x then print "x has a value." end if if not(x) then print "x has no value." end if   ' -------------------------- ' if .. end if if x = 0 then print "Zero" goto [surprise] end if wait   if x = 0 then goto [surprise] print "No surprise." wait   [surprise] print "Surprise!" wait   ' -------------------------- ' case numeric num = 3   select case num case 1 print "one"   case 2 print "two"   case 3 print "three"   case else print "other number"   end select   ' -------------------------- ' case character var$="blue"   select case var$   case "red" print "red"   case "green" print "green"   case else print "color unknown"   end select
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}}} .
#FreeBASIC
FreeBASIC
  #include "gcd.bas" function mul_inv( a as integer, b as integer ) as integer if b = 1 then return 1 for i as integer = 1 to b if a*i mod b = 1 then return i next i return 0 end function   function chinese_remainder(n() as integer, a() as integer) as integer dim as integer p, i, prod = 1, sum = 0, ln = ubound(n) for p = 0 to ln-1 for i = p+1 to ln if gcd(n(i), n(p))>1 then print "N not coprime" end end if next i next p for i = 0 to ln prod *= n(i) next i for i = 0 to ln p = prod/n(i) sum += a(i) * mul_inv(p, n(i))*p next i return sum mod prod end function   dim as integer n(0 to 2) = { 3, 5, 7 } dim as integer a(0 to 2) = { 2, 3, 2 }   print chinese_remainder(n(), a())
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.
#Pascal
Pascal
program Chowla_numbers;   {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}   uses SysUtils {$IFDEF FPC} ,StrUtils{for Numb2USA} {$ENDIF} ;     {$IFNDEF FPC} function Numb2USA(const S: string): string; var I, NA: Integer; begin I := Length(S); Result := S; NA := 0; while (I > 0) do begin if ((Length(Result) - I + 1 - NA) mod 3 = 0) and (I <> 1) then begin Insert(',', Result, I); Inc(NA); end; Dec(I); end; end; {$ENDIF}   function Chowla(n: NativeUint): NativeUint; var Divisor, Quotient: NativeUint; begin result := 0; Divisor := 2; while sqr(Divisor) < n do begin Quotient := n div Divisor; if Quotient * Divisor = n then inc(result, Divisor + Quotient); inc(Divisor); end; if sqr(Divisor) = n then inc(result, Divisor); end;   procedure Count10Primes(Limit: NativeUInt); var n, i, cnt: integer; begin writeln; writeln(' primes til | count'); i := 100; n := 2; cnt := 0; repeat repeat // Ord (true) = 1 ,Ord (false) = 0 inc(cnt, ORD(chowla(n) = 0)); inc(n); until n > i; writeln(Numb2USA(IntToStr(i)): 12, '|', Numb2USA(IntToStr(cnt)): 10); i := i * 10; until i > Limit; end;   procedure CheckPerf; var k, kk, p, cnt, limit: NativeInt; begin writeln; writeln(' number that is perfect'); cnt := 0; limit := 35000000; k := 2; kk := 3; repeat p := k * kk; if p > limit then BREAK; if chowla(p) = (p - 1) then begin writeln(Numb2USA(IntToStr(p)): 12); inc(cnt); end; k := kk + 1; inc(kk, k); until false; end;   var I: integer;   begin for I := 2 to 37 do writeln('chowla(', I: 2, ') =', chowla(I): 3); Count10Primes(10 * 1000 * 1000); CheckPerf; end.
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.
#Ruby
Ruby
def zero(f) return lambda {|x| x} end Zero = lambda { |f| zero(f) }   def succ(n) return lambda { |f| lambda { |x| f.(n.(f).(x)) } } end   Three = succ(succ(succ(Zero)))   def add(n, m) return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } } end   def mult(n, m) return lambda { |f| lambda { |x| m.(n.(f)).(x) } } end   def power(b, e) return e.(b) end   def int_from_couch(f) countup = lambda { |i| i+1 } f.(countup).(0) end   def couch_from_int(x) countdown = lambda { |i| case i when 0 then Zero else succ(countdown.(i-1)) end } countdown.(x) end   Four = couch_from_int(4)   puts [ add(Three, Four), mult(Three, Four), power(Three, Four), power(Four, Three) ].map {|f| int_from_couch(f) }  
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.
#J
J
coclass 'exampleClass'   exampleMethod=: monad define 1+exampleInstanceVariable )   create=: monad define 'this is the constructor' )   exampleInstanceVariable=: 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)
#MATLAB
MATLAB
function [closest,closestpair] = closestPair(xP,yP)   N = numel(xP);   if(N <= 3)   %Brute force closestpair if(N < 2) closest = +Inf; closestpair = {}; else closest = norm(xP{1}-xP{2}); closestpair = {xP{1},xP{2}};   for i = ( 1:N-1 ) for j = ( (i+1):N ) if ( norm(xP{i} - xP{j}) < closest ) closest = norm(xP{i}-xP{j}); closestpair = {xP{i},xP{j}}; end %if end %for end %for end %if (N < 2) else   halfN = ceil(N/2);   xL = { xP{1:halfN} }; xR = { xP{halfN+1:N} }; xm = xP{halfN}(1);   %cellfun( @(p)le(p(1),xm),yP ) is the same as { p ∈ yP : px ≤ xm } yLIndicies = cellfun( @(p)le(p(1),xm),yP );   yL = { yP{yLIndicies} }; yR = { yP{~yLIndicies} };   [dL,pairL] = closestPair(xL,yL); [dR,pairR] = closestPair(xR,yR);   if dL < dR dmin = dL; pairMin = pairL; else dmin = dR; pairMin = pairR; end   %cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) is the same as %{ p ∈ yP : |xm - px| < dmin } yS = {yP{ cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) }}; nS = numel(yS);   closest = dmin; closestpair = pairMin;   for i = (1:nS-1) k = i+1;   while( (k<=nS) && (yS{k}(2)-yS{i}(2) < dmin) )   if norm(yS{k}-yS{i}) < closest closest = norm(yS{k}-yS{i}); closestpair = {yS{k},yS{i}}; end   k = k+1; end %while end %for end %if (N <= 3) end %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
#Scheme
Scheme
;;; Collecting lambdas in a tail-recursive function. (define (build-list-of-functions n i list) (if (< i n) (build-list-of-functions n (+ i 1) (cons (lambda () (* (- n i) (- n i))) list)) list))   (define list-of-functions (build-list-of-functions 10 1 '()))   (map (lambda (f) (f)) list-of-functions)   ((list-ref list-of-functions 8))
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
#Sidef
Sidef
var f = ( 10.of {|i| func(j){i * j} } )   9.times { |j| say f[j](j) }
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
#Haskell
Haskell
add (a, b) (x, y) = (a + x, b + y) sub (a, b) (x, y) = (a - x, b - y) magSqr (a, b) = (a ^^ 2) + (b ^^ 2) mag a = sqrt $ magSqr a mul (a, b) c = (a * c, b * c) div2 (a, b) c = (a / c, b / c) perp (a, b) = (negate b, a) norm a = a `div2` mag a   circlePoints :: (Ord a, Floating a) => (a, a) -> (a, a) -> a -> Maybe ((a, a), (a, a)) circlePoints p q radius | radius == 0 = Nothing | p == q = Nothing | diameter < magPQ = Nothing | otherwise = Just (center1, center2) where diameter = radius * 2 pq = p `sub` q magPQ = mag pq midpoint = (p `add` q) `div2` 2 halfPQ = magPQ / 2 magMidC = sqrt . abs $ (radius ^^ 2) - (halfPQ ^^ 2) midC = (norm $ perp pq) `mul` magMidC center1 = midpoint `add` midC center2 = midpoint `sub` midC   uncurry3 f (a, b, c) = f a b c   main :: IO () main = mapM_ (print . uncurry3 circlePoints) [((0.1234, 0.9876), (0.8765, 0.2345), 2), ((0 , 2 ), (0 , 0 ), 1), ((0.1234, 0.9876), (0.1234, 0.9876), 2), ((0.1234, 0.9876), (0.8765, 0.2345), 0.5), ((0.1234, 0.9876), (0.1234, 0.1234), 0)]
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).
#Go
Go
package main   import "fmt"   var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲乙丙丁戊己庚辛壬癸") branchCh = []rune("子丑寅卯辰巳午未申酉戌亥") )   func cz(yr int) (animal, yinYang, element, stemBranch string, cycleYear int) { yr -= 4 stem := yr % 10 branch := yr % 12 return animalString[branch], stemYYString[stem%2], elementString[stem/2], string([]rune{stemCh[stem], branchCh[branch]}), yr%60 + 1 }   func main() { for _, yr := range []int{1935, 1938, 1968, 1972, 1976} { a, yy, e, sb, cy := cz(yr) fmt.Printf("%d: %s %s, %s, Cycle year %d %s\n", yr, e, a, yy, cy, sb) } }
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
#C
C
#include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <unistd.h>   /* Check for regular file. */ int check_reg(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISREG(sb.st_mode); }   /* Check for directory. */ int check_dir(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode); }   int main() { printf("input.txt is a regular file? %s\n", check_reg("input.txt") ? "yes" : "no"); printf("docs is a directory? %s\n", check_dir("docs") ? "yes" : "no"); printf("/input.txt is a regular file? %s\n", check_reg("/input.txt") ? "yes" : "no"); printf("/docs is a directory? %s\n", check_dir("/docs") ? "yes" : "no"); return 0; }
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
#Delphi
Delphi
  unit main;   interface   uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.ExtCtrls, System.Generics.Collections;   type TColoredPoint = record P: TPoint; Index: Integer; constructor Create(PX, PY: Integer; ColorIndex: Integer); end;   TForm1 = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormPaint(Sender: TObject); private Buffer: TBitmap; Points: array[0..2] of TPoint; Stack: TStack<TColoredPoint>; Tick: TTimer; procedure Run(Sender: TObject); procedure AddPoint; function HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint; { Private declarations } public { Public declarations } end;   const Colors: array[0..2] of Tcolor = (clRed, clGreen, clBlue);   var Form1: TForm1;   implementation   {$R *.dfm}   { TColoredPoint }   constructor TColoredPoint.Create(PX, PY: Integer; ColorIndex: Integer); begin self.P := Tpoint.Create(PX, PY); self.Index := ColorIndex; end;   { TForm1 }   procedure TForm1.FormCreate(Sender: TObject); begin Buffer := TBitmap.Create; Stack := TStack<TColoredPoint>.Create; Tick := TTimer.Create(nil); Caption := 'Chaos Game';   DoubleBuffered := True;   ClientHeight := 640; ClientWidth := 640; var margin := 60; var size := ClientWidth - 2 * margin;   Points[0] := TPoint.Create(ClientWidth div 2, margin); Points[1] := TPoint.Create(margin, size); Points[2] := TPoint.Create(margin + size, size);   Stack.Push(TColoredPoint.Create(-1, -1, Colors[0]));   Tick.Interval := 10; Tick.OnTimer := Run; end;   function TForm1.HalfWayPoint(a: TColoredPoint; b: TPoint; index: Integer): TColoredPoint; begin Result := TColoredPoint.Create((a.p.X + b.x) div 2, (a.p.y + b.y) div 2, index); end;   procedure TForm1.AddPoint; begin var colorIndex := Random(3); var p1 := Stack.Peek; var p2 := Points[colorIndex]; Stack.Push(HalfWayPoint(p1, p2, colorIndex)); end;   procedure TForm1.Run(Sender: TObject); begin if Stack.Count < 50000 then begin for var i := 0 to 999 do AddPoint; Invalidate; end; end;   procedure TForm1.FormDestroy(Sender: TObject); begin Tick.Free; Buffer.Free; Stack.Free; end;   procedure TForm1.FormPaint(Sender: TObject); begin for var p in Stack do begin with Canvas do begin Pen.Color := Colors[p.Index]; Brush.Color := Colors[p.Index]; Brush.Style := bsSolid; Ellipse(p.p.X - 1, p.p.y - 1, p.p.X + 1, p.p.y + 1); end; end; end; 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.
#Go
Go
package main   import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" )   func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) }   // A Server represents a chat server that accepts incoming connections. type Server struct { add chan *conn // To add a connection rem chan string // To remove a connection by name msg chan string // To send a message to all connections stop chan bool // To stop early }   // ListenAndServe listens on the TCP network address addr for // new chat client connections. func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { // TODO use AcceptTCP() so that we can get a TCPConn on which // we can call SetKeepAlive() and SetKeepAlivePeriod() rwc, err := ln.Accept() if err != nil { // TODO Could handle err.(net.Error).Temporary() // here by adding a backoff delay. close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } }   // handleConns is run as a go routine to handle adding and removal of // chat client connections as well as broadcasting messages to them. func (s *Server) handleConns() { // We define the `conns` map here rather than within Server, // and we use local function literals rather than methods to be // extra sure that the only place that touches this map is this // method. In this way we forgo any explicit locking needed as // we're the only go routine that can see or modify this. conns := make(map[string]*conn)   var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) // TODO handle blocked connections for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) // Defer all the disconnect messages until after // we've closed all currently problematic conns. defer dropConn(name) } } }   dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) }   defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }()   for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } }   // A conn represents the server side of a single chat connection. // Note we embed the bufio.Reader and net.Conn (and specifically in // that order) so that a conn gets the appropriate methods from each // to be a full io.ReadWriteCloser. type conn struct { *bufio.Reader // buffered input net.Conn // raw connection server *Server // the Server on which the connection arrived name string }   func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } }   // welcome requests a name from the client before attempting to add the // named connect to the set handled by the server. func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } // The server will take this *conn and do a final check // on the name, possibly starting c.welcome() again. c.server.add <- c }   // readloop is started as a go routine by the server once the initial // welcome phase has completed successfully. It reads single lines from // the client and passes them to the server for broadcast to all chat // clients (including us). // Once done, we ask the server to remove (and close) our connection. func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } //msg = strings.TrimSpace(msg) c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
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.
#Nim
Nim
import bignum   type   # Description of a term. Term = object factor: int # Multiplier (may be negative). fract: Rat # Argument of arc tangent.   Expression = seq[Term]   # Rational 1. let One = newRat(1)     #################################################################################################### # Formula parser.   type   # Possible tokens for parsing. Token = enum tkPi, tkArctan, tkNumber, tkEqual, tkAdd, tkSub, tkMul, tkDiv, tkLPar, tkRPar, tkError, tkEnd   # Lexer description. Lexer = object line: string # The line to parse. pos: Natural # Current position of lexer. token: Token # Current token. value: Natural # Associated value (for numbers).   # Exception raised if an error is found. SyntaxError = object of CatchableError   #---------------------------------------------------------------------------------------------------   proc initLexer(line: string): Lexer = ## Create and initialize a lexer. result.line = line result.pos = 0   #---------------------------------------------------------------------------------------------------   proc parseName(lexer: var Lexer; pos: Natural) = ## Parse a name.   # Build the name. var pos = pos var name = "" while pos < lexer.line.len and (let c = lexer.line[pos]; c) in 'a'..'z': name.add(c) inc pos   # Update lexer state. lexer.token = if name == "arctan": tkArctan elif name == "pi": tkPi else: tkError lexer.pos = pos   #---------------------------------------------------------------------------------------------------   proc parseNumber(lexer: var Lexer; pos: Natural) = ## Parse a number.   # Build the number. var pos = pos var value = 0 while pos < lexer.line.len and (let c = lexer.line[pos]; c) in '0'..'9': value = 10 * value + ord(c) - ord('0') inc pos   # Update lexer state. lexer.token = tkNumber lexer.value = value lexer.pos = pos   #---------------------------------------------------------------------------------------------------   proc getNextToken(lexer: var Lexer) = ## Find next token.   var pos = lexer.pos var token: Token while pos < lexer.line.len and lexer.line[pos] == ' ': inc pos if pos == lexer.line.len: # Reached end of string. lexer.pos = pos lexer.token = tkEnd return   # Find token. case lexer.line[pos] of '=': token = tkEqual of '+': token = tkAdd of '-': token = tkSub of '*': token = tkMul of '/': token = tkDiv of '(': token = tkLPar of ')': token = tkRPar of 'a'..'z': lexer.parseName(pos) return of '0'..'9': lexer.parseNumber(pos) return else: token = tkError   # Update lexer state. lexer.pos = pos + 1 lexer.token = token   #---------------------------------------------------------------------------------------------------   template syntaxError(message: string) = ## Raise a syntax error exception. raise newException(SyntaxError, message)   #---------------------------------------------------------------------------------------------------   proc parseFraction(lexer: var Lexer): Rat = ## Parse a fraction: number / number.   lexer.getNextToken() if lexer.token != tkNumber: syntaxError("number expected.") let num = lexer.value lexer.getNextToken() if lexer.token != tkDiv: syntaxError("“/” expected.") lexer.getNextToken() if lexer.token != tkNumber: syntaxError("number expected") if lexer.value == 0: raise newException(ValueError, "null denominator.") let den = lexer.value result = newRat(num, den)   #---------------------------------------------------------------------------------------------------   proc parseTerm(lexer: var Lexer): Term = ## Parse a term: factor * arctan(fraction) or arctan(fraction).   lexer.getNextToken()   # Parse factor. if lexer.token == tkNumber: result.factor = lexer.value lexer.getNextToken if lexer.token != tkMul: syntaxError("“*” expected.") lexer.getNextToken() else: result.factor = 1   # Parse arctan. if lexer.token != tkArctan: syntaxError("“arctan” expected.") lexer.getNextToken() if lexer.token != tkLPar: syntaxError("“(” expected.") result.fract = lexer.parseFraction() lexer.getNextToken() if lexer.token != tkRPar: syntaxError("“)” expected.")   #---------------------------------------------------------------------------------------------------   proc parse(line: string): Expression = ## Parse a formula.   var lexer = initLexer(line) lexer.getNextToken()   if lexer.token != tkPi: syntaxError("pi symbol expected.") lexer.getNextToken()   if lexer.token != tkDiv: syntaxError("'/' expected.") lexer.getNextToken()   if lexer.token != tkNumber: syntaxError("number expected.") if lexer.value != 4: raise newException(ValueError, "value 4 expected.") lexer.getNextToken()   if lexer.token != tkEqual: syntaxError("“=” expected.") result.add(lexer.parseTerm()) lexer.getNextToken()   # Parse the next terms. while (let token = lexer.token; token) in {tkAdd, tkSub}: var term = lexer.parseTerm() if token == tkSub: term.factor = -term.factor result.add(term) lexer.getNextToken()   if lexer.token != tkEnd: syntaxError("invalid characters at end of formula.")     #################################################################################################### # Evaluator.   proc tangent(factor: int; fract: Rat): Rat = ## Compute the tangent of "factor * arctan(fract)".   if factor == 1: return fract if factor < 0: return -tangent(-factor, fract)   # Split in two parts. let n = factor div 2 let a = tangent(n, fract) let b = tangent(factor - n, fract) result = (a + b) / (One - a * b)   #---------------------------------------------------------------------------------------------------   proc tangent(expr: Expression): Rat = ## Compute the tangent of a sum of terms.   if expr.len == 1: result = tangent(expr[0].factor, expr[0].fract) else: # Split in two parts. let a = tangent(expr[0..<(expr.len div 2)]) let b = tangent(expr[(expr.len div 2)..^1]) result = (a + b) / (One - a * b)   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   const Formulas = [ "pi/4 = arctan(1/2) + arctan(1/3)", "pi/4 = 2*arctan(1/3) + arctan(1/7)", "pi/4 = 4*arctan(1/5) - arctan(1/239)", "pi/4 = 5*arctan(1/7) + 2*arctan(3/79)", "pi/4 = 5*arctan(29/278) + 7*arctan(3/79)", "pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)", "pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)", "pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)", "pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)", "pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)", "pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)", "pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)", "pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)", "pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)", "pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)", "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)", "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)"]   for formula in Formulas: let expr = formula.parse() let value = tangent(expr) if value == 1: echo "True: ", formula else: echo "False: ", formula echo "Tangent of the right expression is about ", value.toFloat
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.
#Axe
Axe
Disp 'a'▶Dec,i Disp 97▶Char,i
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.
#Babel
Babel
'abcdefg' str2ar {%d nl <<} eachar
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.
#Idris
Idris
module Main   import Data.Vect   Matrix : Nat -> Nat -> Type -> Type Matrix m n t = Vect m (Vect n t)     zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double zeros m n = replicate m (replicate n 0.0)     indexM : (Fin m, Fin n) -> Matrix m n t -> t indexM (i, j) a = index j (index i a)     replaceAtM : (Fin m, Fin n) -> t -> Matrix m n t -> Matrix m n t replaceAtM (i, j) e a = replaceAt i (replaceAt j e (index i a)) a     get : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Double get a l (i, j) {m} = if i == j then sqrt $ indexM (j, j) a - dot else if i > j then (indexM (i, j) a - dot) / indexM (j, j) l else 0.0   where -- Obtain indicies 0 to j -1 ks : List (Fin m) ks = case (findIndices (\_ => True) a) of [] => [] (x::xs) => init (x::xs)   dot : Double dot = sum [(indexM (i, k) l) * (indexM (j, k) l) | k <- ks]     updateL : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Matrix m m Double updateL a l idx = replaceAtM idx (get a l idx) l     cholesky : Matrix m m Double -> Matrix m m Double cholesky a {m} = foldl (\l',i => foldl (\l'',j => updateL a l'' (i, j)) l' (js i)) l is where l = zeros m m   is : List (Fin m) is = findIndices (\_ => True) a   js : Fin m -> List (Fin m) js n = filter (<= n) is     ex1 : Matrix 3 3 Double ex1 = cholesky [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]]   ex2 : Matrix 4 4 Double ex2 = cholesky [[18.0, 22.0, 54.0, 42.0], [22.0, 70.0, 86.0, 62.0], [54.0, 86.0, 174.0, 134.0], [42.0, 62.0, 134.0, 106.0]]   main : IO () main = do print ex1 putStrLn "\n" print ex2 putStrLn "\n"  
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.
#J
J
mp=: +/ . * NB. matrix product h =: +@|: NB. conjugate transpose   cholesky=: 3 : 0 n=. #A=. y if. 1>:n do. assert. (A=|A)>0=A NB. check for positive definite  %:A else. 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 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
#Java
Java
import java.time.Month; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors;   public class Main { private static class Birthday { private Month month; private int day;   public Birthday(Month month, int day) { this.month = month; this.day = day; }   public Month getMonth() { return month; }   public int getDay() { return day; }   @Override public String toString() { return month + " " + day; } }   public static void main(String[] args) { List<Birthday> choices = List.of( 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) ); System.out.printf("There are %d candidates remaining.\n", choices.size());   // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer Set<Month> uniqueMonths = choices.stream() .collect(Collectors.groupingBy(Birthday::getDay)) .values() .stream() .filter(g -> g.size() == 1) .flatMap(Collection::stream) .map(Birthday::getMonth) .collect(Collectors.toSet()); List<Birthday> f1List = choices.stream() .filter(birthday -> !uniqueMonths.contains(birthday.month)) .collect(Collectors.toList()); System.out.printf("There are %d candidates remaining.\n", f1List.size());   // Bernard now knows the answer, so the day must be unique within the remaining choices List<Birthday> f2List = f1List.stream() .collect(Collectors.groupingBy(Birthday::getDay)) .values() .stream() .filter(g -> g.size() == 1) .flatMap(Collection::stream) .collect(Collectors.toList()); System.out.printf("There are %d candidates remaining.\n", f2List.size());   // Albert knows the answer too, so the month must be unique within the remaining choices List<Birthday> f3List = f2List.stream() .collect(Collectors.groupingBy(Birthday::getMonth)) .values() .stream() .filter(g -> g.size() == 1) .flatMap(Collection::stream) .collect(Collectors.toList()); System.out.printf("There are %d candidates remaining.\n", f3List.size());   if (f3List.size() == 1) { System.out.printf("Cheryl's birthday is %s\n", f3List.get(0)); } 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.
#Python
Python
  """   Based on https://pymotw.com/3/threading/   """   import threading import time import random     def worker(workernum, barrier): # task 1 sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() # task 2 sleeptime = random.random() print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum))   barrier = threading.Barrier(3)   w1 = threading.Thread(target=worker, args=((1,barrier))) w2 = threading.Thread(target=worker, args=((2,barrier))) w3 = threading.Thread(target=worker, args=((3,barrier)))   w1.start() w2.start() w3.start()  
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
#jq
jq
{"a": 1} == {a: 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
#Oz
Oz
declare fun {Comb M N} proc {CombScript Comb} %% Comb is a subset of [0..N-1] Comb = {FS.var.upperBound {List.number 0 N-1 1}} %% Comb has cardinality M {FS.card Comb M} %% enumerate all possibilities {FS.distribute naive [Comb]} end in %% Collect all solutions and convert to lists {Map {SearchAll CombScript} FS.reflect.upperBoundList} end in {Inspect {Comb 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.
#Run_BASIC
Run BASIC
' Boolean Evaluations ' ' > Greater Than ' < Less Than ' >= Greater Than Or Equal To ' <= Less Than Or Equal To ' = Equal to   x = 0   if x = 0 then print "Zero"   ' -------------------------- ' if/then/else if x = 0 then print "Zero" else print "Nonzero" end if   ' -------------------------- ' not if x then print "x has a value." end if if not(x) then print "x has no value." end if   ' -------------------------- ' if .. end if if x = 0 then print "Zero" goto [surprise] end if wait   if x = 0 then goto [surprise] print "No surprise." wait   [surprise] print "Surprise!" wait   ' -------------------------- ' case numeric num = 3   select case num case 1 print "one"   case 2 print "two"   case 3 print "three"   case else print "other number"   end select   ' -------------------------- ' case character var$="blue"   select case var$   case "red" print "red"   case "green" print "green"   case else print "color unknown"   end select
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}}} .
#Frink
Frink
/** arguments: [r, m, d=0] where r and m are arrays of the remainder terms r and the modulus terms m respectively. These must be of the same length. returns x, the unique solution mod N where N is the product of all the M terms where x &gt;= d. */ ChineseRemainder[r, m, d=0] := { if length[r] != length[m] { println["ChineseRemainder: r and m must be arrays of the same length."] return undef }   N = product[m]   y = new array z = new array x = 0 for i = rangeOf[m] { y@i = N / m@i z@i = modInverse[y@i, m@i] if z@i == undef { println["ChineseRemainder: modInverse returned undef for modInverse[" + y@i + ", " + m@i + "]"] return undef }   x = x + r@i y@i z@i }   xp = x mod N f = d div N r = f * N + xp if r < d r = r + N   return r }   println[ChineseRemainder[[2,3,2],[3,5,7]] ]
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}}} .
#FunL
FunL
import integers.modinv   def crt( congruences ) = N = product( n | (_, n) <- congruences ) sum( a*modinv(N/n, n)*N/n | (a, n) <- congruences ) mod N   println( crt([(2, 3), (3, 5), (2, 7)]) )
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.
#Perl
Perl
use strict; use warnings; use ntheory 'divisor_sum';   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub chowla { my($n) = @_; $n < 2 ? 0 : divisor_sum($n) - ($n + 1); }   sub prime_cnt { my($n) = @_; my $cnt = 1; for (3..$n) { $cnt++ if $_%2 and chowla($_) == 0 } $cnt; }   sub perfect { my($n) = @_; my @p; for my $i (1..$n) { push @p, $i if $i > 1 and chowla($i) == $i-1; } # map { push @p, $_ if $_ > 1 and chowla($_) == $_-1 } 1..$n; # speed penalty @p; }   printf "chowla(%2d) = %2d\n", $_, chowla($_) for 1..37; print "\nCount of primes up to:\n"; printf "%10s %s\n", comma(10**$_), comma(prime_cnt(10**$_)) for 2..7; my @perfect = perfect(my $limit = 35_000_000); printf "\nThere are %d perfect numbers up to %s: %s\n", 1+$#perfect, comma($limit), join(' ', map { comma($_) } @perfect);
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.
#Rust
Rust
use std::rc::Rc; use std::ops::{Add, Mul};   #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, }   impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }) } }   fn succ(self) -> Self { Church { runner: Rc::new(move |f| { let g = self.runner.clone(); Rc::new(move |x| f(g(f.clone())(x))) }) } }   fn run(&self, f: impl Fn(T) -> T + 'a) -> Rc<dyn Fn(T) -> T + 'a> { (self.runner)(Rc::new(f)) }   fn exp(self, rhs: Church<'a, Rc<dyn Fn(T) -> T + 'a>>) -> Self { Church { runner: (rhs.runner)(self.runner) } } }   impl<'a, T> Add for Church<'a, T> { type Output = Church<'a, T>;   fn add(self, rhs: Church<'a, T>) -> Church<T> { Church { runner: Rc::new(move |f| { let self_runner = self.runner.clone(); let rhs_runner = rhs.runner.clone(); Rc::new(move |x| (self_runner)(f.clone())((rhs_runner)(f.clone())(x))) }) } } }   impl<'a, T> Mul for Church<'a, T> { type Output = Church<'a, T>;   fn mul(self, rhs: Church<'a, T>) -> Church<T> { Church { runner: Rc::new(move |f| { (self.runner)((rhs.runner)(f)) }) } } }   impl<'a, T> From<i32> for Church<'a, T> { fn from(n: i32) -> Church<'a, T> { let mut ret = Church::zero(); for _ in 0..n { ret = ret.succ(); } ret } }   impl<'a> From<&Church<'a, i32>> for i32 { fn from(c: &Church<'a, i32>) -> i32 { c.run(|x| x + 1)(0) } }   fn three<'a, T>() -> Church<'a, T> { Church::zero().succ().succ().succ() }   fn four<'a, T>() -> Church<'a, T> { Church::zero().succ().succ().succ().succ() }   fn main() { println!("three =\t{}", i32::from(&three())); println!("four =\t{}", i32::from(&four()));   println!("three + four =\t{}", i32::from(&(three() + four()))); println!("three * four =\t{}", i32::from(&(three() * four())));   println!("three ^ four =\t{}", i32::from(&(three().exp(four())))); println!("four ^ three =\t{}", i32::from(&(four().exp(three())))); }
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.
#Standard_ML
Standard ML
  val demo = fn () => let open IntInf   val zero = fn f => fn x => x ; fun succ n = fn f => f o (n f)  ; (* successor *) val rec church = fn 0 => zero | n => succ ( church (n-1) ) ; (* natural to church numeral *) val natural = fn churchn => churchn (fn x => x+1) (fromInt 0) ; (* church numeral to natural *)   val mult = fn cn => fn cm => cn o cm  ; val add = fn cn => fn cm => fn f => (cn f) o (cm f) ; val exp = fn cn => fn em => em cn;   in   List.app (fn i=>print( (toString i)^"\n" )) ( List.map natural [ add (church 3) (church 4) , mult (church 3) (church 4) , exp (church 4) (church 3) , exp (church 3) (church 4) ] )   end;  
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.
#Java
Java
public class MyClass{   // instance variable private int variable; // Note: instance variables are usually "private"   /** * The constructor */ public MyClass(){ // creates a new instance }   /** * A method */ public void someMethod(){ this.variable = 1; } }
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.
#JavaScript
JavaScript
//Constructor function. function Car(brand, weight) { this.brand = brand; this.weight = weight || 1000; // Resort to default value (with 'or' notation). } Car.prototype.getPrice = function() { // Method of Car. return this.price; }   function Truck(brand, size) { this.car = Car; this.car(brand, 2000); // Call another function, modifying the "this" object (e.g. "superconstructor".) this.size = size; // Custom property for just this object. } Truck.prototype = Car.prototype; // Also "import" the prototype from Car.   var cars = [ // Some example car objects. new Car("Mazda"), new Truck("Volvo", 2) ]; for (var i=0; i<cars.length; i++) { alert(cars[i].brand + " " + cars[i].weight + " " + cars[i].size + ", " + (cars[i] instanceof Car) + " " + (cars[i] instanceof Truck)); }
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)
#Microsoft_Small_Basic
Microsoft Small Basic
' Closest Pair Problem s="0.654682,0.925557,0.409382,0.619391,0.891663,0.888594,0.716629,0.996200,0.477721,0.946355,0.925092,0.818220,0.624291,0.142924,0.211332,0.221507,0.293786,0.691701,0.839186,0.728260," i=0 While s<>"" i=i+1 For j=1 To 2 k=Text.GetIndexOf(s,",") ss=Text.GetSubText(s,1,k-1) s=Text.GetSubTextToEnd(s,k+1) pxy[i][j]=ss EndFor EndWhile n=i i=1 j=2 dd=Math.Power(pxy[i][1]-pxy[j][1],2)+Math.Power(pxy[i][2]-pxy[j][2],2) ddmin=dd ii=i jj=j For i=1 To n For j=1 To n dd=Math.Power(pxy[i][1]-pxy[j][1],2)+Math.Power(pxy[i][2]-pxy[j][2],2) If dd>0 Then If dd<ddmin Then ddmin=dd ii=i jj=j EndIf EndIf EndFor EndFor sqrt1=ddmin sqrt2=ddmin/2 For i=1 To 20 If sqrt1=sqrt2 Then Goto exitfor EndIf sqrt1=sqrt2 sqrt2=(sqrt1+(ddmin/sqrt1))/2 EndFor exitfor: TextWindow.WriteLine("the minimum distance "+sqrt2) TextWindow.WriteLine("is between the points:") TextWindow.WriteLine(" ["+pxy[ii][1]+","+pxy[ii][2]+"] and") TextWindow.WriteLine(" ["+pxy[jj][1]+","+pxy[jj][2]+"]")
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
#Smalltalk
Smalltalk
funcs := (1 to: 10) collect: [ :i | [ i * i ] ] . (funcs at: 3) value displayNl .
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
#Sparkling
Sparkling
var fnlist = {}; for var i = 0; i < 10; i++ { fnlist[i] = function() { return i * i; }; }   print(fnlist[3]()); // prints 9 print(fnlist[5]()); // prints 25
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
#Icon_and_Unicon
Icon and Unicon
procedure main() A := [ [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.9765, 0.2345, 0.5], [0.1234, 0.9876, 0.1234, 0.9876, 0.0] ] every write(cCenter!!A) end   procedure cCenter(x1,y1, x2,y2, r) if r <= 0 then return "Illegal radius" r2 := r*2 d := ((x2-x1)^2 + (y2-y1)^2)^0.5 if d = 0 then return "Identical points, infinite number of circles" if d > r2 then return "No circles possible" z := (r^2-(d/2.0)^2)^0.5 x3 := (x1+x2)/2.0; y3 := (y1+y2)/2.0 cx1 := x3+z*(y1-y2)/d; cy1 := y3+z*(x2-x1)/d cx2 := x3-z*(y1-y2)/d; cy2 := y3-z*(x2-x1)/d if d = r2 then return "Single circle at ("||cx1||","||cy1||")" return "("||cx1||","||cy1||") and ("||cx2||","||cy2||")" end
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).
#Groovy
Groovy
class Zodiac { final static String[] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] final static String[] elements = ["Wood", "Fire", "Earth", "Metal", "Water"] final static String[] animalChars = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"] static String[][] elementChars = [["甲", "丙", "戊", "庚", "壬"], ["乙", "丁", "己", "辛", "癸"]]   static String getYY(int year) { if (year % 2 == 0) { return "yang" } else { return "yin" } }   static void main(String[] args) { int[] years = [1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017] for (int i = 0; i < years.length; i++) { println(years[i] + " is the year of the " + elements[(int) Math.floor((years[i] - 4) % 10 / 2)] + " " + animals[(years[i] - 4) % 12] + " (" + getYY(years[i]) + "). " + elementChars[years[i] % 2][(int) Math.floor((years[i] - 4) % 10 / 2)] + animalChars[(years[i] - 4) % 12]) } } }
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
#C.23
C#
using System.IO;   Console.WriteLine(File.Exists("input.txt")); Console.WriteLine(File.Exists("/input.txt")); Console.WriteLine(Directory.Exists("docs")); Console.WriteLine(Directory.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
#C.2B.2B
C++
#include "boost/filesystem.hpp" #include <string> #include <iostream>   void testfile(std::string name) { boost::filesystem::path file(name); if (exists(file)) { if (is_directory(file)) std::cout << name << " is a directory.\n"; else std::cout << name << " is a non-directory file.\n"; } else std::cout << name << " does not exist.\n"; }   int main() { testfile("input.txt"); testfile("docs"); testfile("/input.txt"); testfile("/docs"); }
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
#EasyLang
EasyLang
color 900 x[] = [ 0 100 50 ] y[] = [ 93 93 7 ] x = randomf * 100 y = randomf * 100 for i range 100000 move x y rect 0.3 0.3 h = random 3 x = (x + x[h]) / 2 y = (y + y[h]) / 2 .
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
#Emacs_Lisp
Emacs Lisp
; Chaos game   (defun make-array (size) "Create an empty array with size*size elements." (setq m-array (make-vector size nil)) (dotimes (i size) (setf (aref m-array i) (make-vector size 0))) m-array)   (defun chaos-next (p) "Return the next coordinates." (let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3)))) (v (elt points (random 3))) (x (car p)) (y (cdr p)) (x2 (car v)) (y2 (cdr v))) (setq nx (/ (+ x x2) 2.0)) (setq ny (/ (+ y y2) 2.0)) (cons nx ny)))   (defun chaos-lines (arr size) "Turn array into a string for XPM conversion." (setq all "") (dotimes (y size) (setq line "") (dotimes (x size) (setq line (concat line (if (= (elt (elt arr y) x) 1) "*" ".")))) (setq all (concat all "\"" line "\",\n"))) all)   (defun chaos-show (arr size) "Convert size*size array to XPM image and show it." (insert-image (create-image (concat (format "/* XPM */ static char * chaos[] = { \"%i %i 2 1\", \". c #000000\", \"* c #00ff00\"," size size) (chaos-lines arr size) "};") 'xpm t)))   (defun chaos (size scale max-iter) "Play the chaos game." (let ((arr (make-array size)) (p (cons 0 0))) (dotimes (it max-iter) (setq p (chaos-next p)) (setq x (round (+ (/ size 2) (* scale (car p))))) (setq y (round (+ (- size 10) (* -1 scale (cdr p))))) (setf (elt (elt arr y) x) 1)) (chaos-show arr size)))   (chaos 400 180 50000)
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.
#Groovy
Groovy
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>()   ChatServer(int port) { this.port = port }   @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } }   private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true }   private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } }   private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() }   private void broadcast(Client fromClient, String msg) { // Copy client list (don't want to hold lock while doing IO) List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { // empty } } }   class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null   Client(Socket socket) { this.socket = socket }   @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { // empty } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { // empty } socket = null } }   void write(String msg) { output.write(msg) output.flush() }   @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName }   @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } }   static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
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.
#OCaml
OCaml
open Num;; (* use exact rationals for results *)   let tadd p q = (p +/ q) // ((Int 1) -/ (p */ q)) in   (* tan(n*arctan(a/b)) *) let rec tan_expr (n,a,b) = if n = 1 then (Int a)//(Int b) else if n = -1 then (Int (-a))//(Int b) else let m = n/2 in let tm = tan_expr (m,a,b) in let m2 = tadd tm tm and k = n-m-m in if k = 0 then m2 else tadd (tan_expr (k,a,b)) m2 in   let verify (k, tlist) = Printf.printf "Testing: pi/%d = " k; let t_str = List.map (fun (x,y,z) -> Printf.sprintf "%d*atan(%d/%d)" x y z) tlist in print_endline (String.concat " + " t_str); let ans_terms = List.map tan_expr tlist in let answer = List.fold_left tadd (Int 0) ans_terms in Printf.printf " tan(RHS) is %s\n" (if answer = (Int 1) then "one" else "not one") in   (* example: prog 4 5 29 278 7 3 79 represents pi/4 = 5*atan(29/278) + 7*atan(3/79) *) let args = Sys.argv in let nargs = Array.length args in let v k = int_of_string args.(k) in let rec triples n = if n+2 > nargs-1 then [] else (v n, v (n+1), v (n+2)) :: triples (n+3) in if nargs > 4 then let dat = (v 1, triples 2) in verify dat else List.iter verify [ (4,[(1,1,2);(1,1,3)]); (4,[(2,1,3);(1,1,7)]); (4,[(4,1,5);(-1,1,239)]); (4,[(5,1,7);(2,3,79)]); (4,[(5,29,278);(7,3,79)]); (4,[(1,1,2);(1,1,5);(1,1,8)]); (4,[(4,1,5);(-1,1,70);(1,1,99)]); (4,[(5,1,7);(4,1,53);(2,1,4443)]); (4,[(6,1,8);(2,1,57);(1,1,239)]); (4,[(8,1,10);(-1,1,239);(-4,1,515)]); (4,[(12,1,18);(8,1,57);(-5,1,239)]); (4,[(16,1,21);(3,1,239);(4,3,1042)]); (4,[(22,1,28);(2,1,443);(-5,1,1393);(-10,1,11018)]); (4,[(22,1,38);(17,7,601);(10,7,8149)]); (4,[(44,1,57);(7,1,239);(-12,1,682);(24,1,12943)]); (4,[(88,1,172);(51,1,239);(32,1,682);(44,1,5357);(68,1,12943)]); (4,[(88,1,172);(51,1,239);(32,1,682);(44,1,5357);(68,1,12944)]) ]
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.
#BASIC
BASIC
charCode = 97 char = "a" PRINT CHR$(charCode) 'prints a PRINT ASC(char) '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.
#BASIC256
BASIC256
# ASCII char charCode = 97 char$ = "a" print chr(97) #prints a print asc("a") #prints 97   # Unicode char charCode = 960 char$ = "π" print chr(960) #prints π print asc("π") #prints 960
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.
#Java
Java
import java.util.Arrays;   public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m]; //automatically initialzed to 0's for(int i = 0; i< m;i++){ for(int k = 0; k < (i+1); k++){ double sum = 0; for(int j = 0; j < k; j++){ sum += l[i][j] * l[k][j]; } l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) : (1.0 / l[k][k] * (a[i][k] - sum)); } } return l; }   public static void main(String[] args){ double[][] test1 = {{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}; System.out.println(Arrays.deepToString(chol(test1))); double[][] test2 = {{18, 22, 54, 42}, {22, 70, 86, 62}, {54, 86, 174, 134}, {42, 62, 134, 106}}; System.out.println(Arrays.deepToString(chol(test2))); } }
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
#JavaScript
JavaScript
(() => { 'use strict';   // main :: IO () const main = () => { const month = fst, day = snd; showLog( map(x => Array.from(x), (   // The month with only one remaining day,   // (A's month contains only one remaining day) // (3 :: A "Then I also know") uniquePairing(month)(   // among the days with unique months,   // (B's day is paired with only one remaining month) // (2 :: B "I know now") uniquePairing(day)(   // excluding months with unique days,   // (A's month is not among those with unique days) // (1 :: A "I know that Bernard does not know") monthsWithUniqueDays(false)(   // from the given month-day pairs:   // (0 :: Cheryl's list) map(x => tupleFromList(words(strip(x))), splitOn(/,\s+/, `May 15, May 16, May 19, June 17, June 18, July 14, July 16, Aug 14, Aug 15, Aug 17` ) ) ) ) ) )) ); };   // monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)] const monthsWithUniqueDays = blnInclude => xs => { const months = map(fst, uniquePairing(snd)(xs)); return filter( md => (blnInclude ? id : not)( elem(fst(md), months) ), xs ); };   // uniquePairing :: ((a, a) -> a) -> // -> [(Month, Day)] -> [(Month, Day)] const uniquePairing = f => xs => bindPairs(xs, md => { const dct = f(md), matches = filter( k => 1 === length(dct[k]), Object.keys(dct) ); return filter(tpl => elem(f(tpl), matches), xs); } );   // bindPairs :: [(Month, Day)] -> (Dict, Dict) -> [(Month, Day)] const bindPairs = (xs, f) => f( Tuple( dictFromPairs(fst)(snd)(xs), dictFromPairs(snd)(fst)(xs) ) );   // dictFromPairs :: ((a, a) -> a) -> ((a, a) -> a) -> [(a, a)] -> Dict const dictFromPairs = f => g => xs => foldl((a, tpl) => Object.assign( a, { [f(tpl)]: (a[f(tpl)] || []).concat(g(tpl).toString()) } ), {}, xs);     // GENERIC ABSTRACTIONS -------------------------------   // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // elem :: Eq a => a -> [a] -> Bool const elem = (x, xs) => xs.includes(x);   // filter :: (a -> Bool) -> [a] -> [a] const filter = (f, xs) => xs.filter(f);   // foldl :: (a -> b -> a) -> a -> [b] -> a const foldl = (f, a, xs) => xs.reduce(f, a);   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // id :: a -> a const id = x => x;   // intersect :: (Eq a) => [a] -> [a] -> [a] const intersect = (xs, ys) => xs.filter(x => -1 !== ys.indexOf(x));   // Returns Infinity over objects without finite length // this enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc   // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f);   // not :: Bool -> Bool const not = b => !b;   // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') );   // snd :: (a, b) -> b const snd = tpl => tpl[1];   // splitOn :: String -> String -> [String] const splitOn = (pat, src) => src.split(pat);   // strip :: String -> String const strip = s => s.trim();   // tupleFromList :: [a] -> (a, a ...) const tupleFromList = xs => TupleN.apply(null, xs);   // TupleN :: a -> b ... -> (a, b ... ) function TupleN() { const args = Array.from(arguments), lng = args.length; return lng > 1 ? Object.assign( args.reduce((a, x, i) => Object.assign(a, { [i]: x }), { type: 'Tuple' + (2 < lng ? lng.toString() : ''), length: lng }) ) : args[0]; };   // words :: String -> [String] const words = s => s.split(/\s+/);   // MAIN --- return main(); })();
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.
#Racket
Racket
  #lang racket (define t 5)  ; total number of threads (define count 0) ; number of threads arrived at rendezvous (define mutex (make-semaphore 1)) ; exclusive access to count (define turnstile (make-semaphore 0)) (define turnstile2 (make-semaphore 1)) (define ch (make-channel))   (define (make-producer name start) (λ () (let loop ([n start]) (sleep (* 0.01 (random 10))) ; "compute" something  ;; rendezvous (semaphore-wait mutex) (set! count (+ count 1)) ; we have arrived (when (= count t) ; are we the last to arrive? (semaphore-wait turnstile2) (semaphore-post turnstile)) (semaphore-post mutex)  ; avoid deadlock problem: (semaphore-wait turnstile) (semaphore-post turnstile)  ; critical point (channel-put ch n) ; send result to controller  ; leave properly (semaphore-wait mutex) (set! count (- count 1)) (when (= count 0) ; are we the last to leave? (semaphore-wait turnstile) (semaphore-post turnstile2)) (semaphore-post mutex)   (semaphore-wait turnstile2) (semaphore-post turnstile2)   (loop (+ n t)))))   ; start t workers: (map (λ(start) (thread (make-producer start start))) (range 0 t))   (let loop () (displayln (for/list ([_ t]) (channel-get ch))) (loop))  
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.
#Raku
Raku
my $TotalWorkers = 3; my $BatchToRun = 3; my @TimeTaken = (5..15); # in seconds   my $batch_progress = 0; my @batch_lock = map { Semaphore.new(1) } , ^$TotalWorkers; my $lock = Lock.new;   sub assembly_line ($ID) { my $wait; for ^$BatchToRun -> $j { $wait = @TimeTaken.roll; say "Worker ",$ID," at batch $j will work for ",$wait," seconds .."; sleep($wait); $lock.protect: { my $k = ++$batch_progress; print "Worker ",$ID," is done and update batch $j complete counter "; say "to $k of $TotalWorkers"; if ($batch_progress == $TotalWorkers) { say ">>>>> batch $j completed."; $batch_progress = 0; # reset for next batch for @batch_lock { .release }; # and ready for next batch }; };   @batch_lock[$ID].acquire; # for next batch } }   for ^$TotalWorkers -> $i { Thread.start( sub { @batch_lock[$i].acquire; assembly_line($i); } ); }
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
#Julia
Julia
    julia> collection = [] 0-element Array{Any,1}   julia> push!(collection, 1,2,4,7) 4-element Array{Any,1}: 1 2 4 7  
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
#PARI.2FGP
PARI/GP
Crv ( k, v, d ) = { if( d == k, print ( vecextract( v , "2..-2" ) ) , for( i = v[ d + 1 ] + 1, #v, v[ d + 2 ] = i; Crv( k, v, d + 1 ) )); }   combRV( n, k ) = Crv ( k, vector( n, X, X-1), 0 );
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.
#Rust
Rust
// This function will only be compiled if we are compiling on Linux #[cfg(target_os = "linux")] fn running_linux() { println!("This is linux"); } #[cfg(not(target_os = "linux"))] fn running_linux() { println!("This is not linux"); }   // If we are on linux, we must be using glibc #[cfg_attr(target_os = "linux", target_env = "gnu")] // We must either be compiling for ARM or on a little endian machine that doesn't have 32-bit pointers pointers, on a // UNIX like OS and only if we are doing a test build #[cfg(all( any(target_arch = "arm", target_endian = "little"), not(target_pointer_width = "32"), unix, test ))] fn highly_specific_function() {}  
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}}} .
#Go
Go
package main   import ( "fmt" "math/big" )   var one = big.NewInt(1)   func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil }   func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
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.
#Phix
Phix
function chowla(atom n) return sum(factors(n)) end function function sieve(integer limit) -- True denotes composite, false denotes prime. -- Only interested in odd numbers >= 3 sequence c = repeat(false,limit) for i=3 to floor(limit/3) by 2 do -- if not c[i] and chowla(i)==0 then if not c[i] then -- (see note below) for j=3*i to limit by 2*i do c[j] = true end for end if end for return c end function atom limit = 1e7, count = 1, pow10 = 100, t0 = time() sequence s = {} for i=1 to 37 do s &= chowla(i) end for printf(1,"chowla[1..37]: %V\n",{s}) s = sieve(limit) for i=3 to limit by 2 do if not s[i] then count += 1 end if if i==pow10-1 then printf(1,"Count of primes up to %,d = %,d\n", {pow10, count}) pow10 *= 10 end if end for count = 0 limit = iff(machine_bits()=32?1.4e11:2.4e18) --limit = power(2,iff(machine_bits()=32?53:64)) -- (see note below) integer i=2 while true do atom p = power(2,i-1)*(power(2,i)-1) -- perfect numbers must be of this form if p>limit then exit end if if chowla(p)==p-1 then printf(1,"%,d is a perfect number\n", p) count += 1 end if i += 1 end while printf(1,"There are %d perfect numbers <= %,d\n",{count,limit}) ?elapsed(time()-t0)
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.
#Swift
Swift
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B { return {f in return {x in return f(n(f)(x)) } } }   func zero<A, B>(_ a: A) -> (B) -> B { return {b in return b } }   func three<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in return succ(succ(succ(zero)))(f)(x) } }   func four<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in return succ(succ(succ(succ(zero))))(f)(x) } }   func add<A, B, C>(_ m: @escaping (B) -> (A) -> C) -> (@escaping (B) -> (C) -> A) -> (B) -> (C) -> C { return {n in return {f in return {x in return m(f)(n(f)(x)) } } } }   func mult<A, B, C>(_ m: @escaping (A) -> B) -> (@escaping (C) -> A) -> (C) -> B { return {n in return {f in return m(n(f)) } } }   func exp<A, B, C>(_ m: A) -> (@escaping (A) -> (B) -> (C) -> C) -> (B) -> (C) -> C { return {n in return {f in return {x in return n(m)(f)(x) } } } }   func church<A>(_ x: Int) -> (@escaping (A) -> A) -> (A) -> A { guard x != 0 else { return zero }   return {f in return {a in return f(church(x - 1)(f)(a)) } } }   func unchurch<A>(_ f: (@escaping (Int) -> Int) -> (Int) -> A) -> A { return f({i in return i + 1 })(0) }   let a = unchurch(add(three)(four)) let b = unchurch(mult(three)(four)) // We can even compose operations let c = unchurch(exp(mult(four)(church(1)))(three)) let d = unchurch(exp(mult(three)(church(1)))(four))   print(a, b, c, d)
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.
#Tailspin
Tailspin
  processor ChurchZero templates apply&{f:} $ ! end apply end ChurchZero   def zero: $ChurchZero;   processor Successor def predecessor: $; templates apply&{f:} $ -> predecessor::apply&{f: f} -> f ! end apply end Successor   templates churchFromInt @: $zero; $ -> # when <=0> do $@! when <1..> do @: $@ -> Successor; $-1 -> # end churchFromInt   templates intFromChurch templates add1 $ + 1 ! end add1 def church: $; 0 -> church::apply&{f: add1} ! end intFromChurch   def three: $zero -> Successor -> Successor -> Successor; def four: 4 -> churchFromInt;   processor Add&{to:} def add: $; templates apply&{f:} $ -> add::apply&{f: f} -> to::apply&{f: f} ! end apply end Add   $three -> Add&{to: $four} -> intFromChurch -> '$; ' -> !OUT::write   processor Multiply&{by:} def multiply: $; templates apply&{f:} $ -> multiply::apply&{f: by::apply&{f: f}} ! end apply end Multiply   $three -> Multiply&{by: $four} -> intFromChurch -> '$; ' -> !OUT::write   processor Power&{exp:} def base: $; templates apply&{f:} processor Wrap&{f:} templates function $ -> f ! end function end Wrap templates compose def p:$; $Wrap&{f: base::apply&{f: p::function}} ! end compose def pow: $Wrap&{f: f} -> exp::apply&{f: compose}; $ -> pow::function ! end apply end Power   $three -> Power&{exp: $four} -> intFromChurch -> '$; ' -> !OUT::write   $four -> Power&{exp: $three} -> intFromChurch -> '$; ' -> !OUT::write  
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.
#Julia
Julia
abstract type Mammal end habitat(::Mammal) = "planet Earth"   struct Whale <: Mammal mass::Float64 habitat::String end Base.show(io::IO, ::Whale) = print(io, "a whale") habitat(w::Whale) = w.habitat   struct Wolf <: Mammal mass::Float64 end Base.show(io::IO, ::Wolf) = print(io, "a wolf")   arr = [Whale(1000, "ocean"), Wolf(50)] println("Type of $arr is ", typeof(arr)) for a in arr println("Habitat of $a: ", habitat(a)) end
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.
#Kotlin
Kotlin
class MyClass(val myInt: Int) { fun treble(): Int = myInt * 3 }   fun main(args: Array<String>) { val mc = MyClass(24) print("${mc.myInt}, ${mc.treble()}") }
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)
#Nim
Nim
import math, algorithm   type   Point = tuple[x, y: float] Pair = tuple[p1, p2: Point] Result = tuple[minDist: float; minPoints: Pair]   #---------------------------------------------------------------------------------------------------   template sqr(x: float): float = x * x   #---------------------------------------------------------------------------------------------------   func dist(point1, point2: Point): float = sqrt(sqr(point2.x - point1.x) + sqr(point2.y - point1.y))   #---------------------------------------------------------------------------------------------------   func bruteForceClosestPair*(points: openArray[Point]): Result =   doAssert(points.len >= 2, "At least two points required.")   result.minDist = Inf for i in 0..<points.high: for j in (i + 1)..points.high: let d = dist(points[i], points[j]) if d < result.minDist: result = (d, (points[i], points[j]))   #---------------------------------------------------------------------------------------------------   func closestPair(xP, yP: openArray[Point]): Result = ## Recursive function which takes two open arrays as arguments: the first ## sorted by increasing values of x, the second sorted by increasing values of y.   if xP.len <= 3: return xP.bruteForceClosestPair()   let m = xP.high div 2 let xL = xP[0..m] let xR = xP[(m + 1)..^1]   let xm = xP[m].x var yL, yR: seq[Point] for p in yP: if p.x <= xm: yL.add(p) else: yR.add(p)   let (dL, pairL) = closestPair(xL, yL) let (dR, pairR) = closestPair(xR, yR) let (dMin, pairMin) = if dL < dR: (dL, pairL) else: (dR, pairR)   var yS: seq[Point] for p in yP: if abs(xm - p.x) < dmin: yS.add(p)   result = (dMin, pairMin) for i in 0..<yS.high: var k = i + 1 while k < yS.len and ys[k].y - yS[i].y < dMin: let d = dist(yS[i], yS[k]) if d < result.minDist: result = (d, (yS[i], yS[k])) inc k   #---------------------------------------------------------------------------------------------------   func closestPair*(points: openArray[Point]): Result =   let xP = points.sortedByIt(it.x) let yP = points.sortedByIt(it.y) doAssert(points.len >= 2, "At least two points required.")   result = closestPair(xP, yP)   #———————————————————————————————————————————————————————————————————————————————————————————————————   import random, times, strformat   randomize()   const N = 50_000 const Max = 10_000.0 var points: array[N, Point] for pt in points.mitems: pt = (rand(Max), rand(Max))   echo "Sample contains ", N, " random points." echo ""   let t0 = getTime() echo "Brute force algorithm:" echo points.bruteForceClosestPair() let t1 = getTime() echo "Optimized algorithm:" echo points.closestPair() let t2 = getTime()   echo "" echo fmt"Execution time for brute force algorithm: {(t1 - t0).inMilliseconds:>4} ms" echo fmt"Execution time for optimized algorithm: {(t2 - t1).inMilliseconds:>4} ms"
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
#Standard_ML
Standard ML
  List.map (fn x => x () ) ( List.tabulate (10,(fn i => (fn ()=> i*i)) ) ) ;  
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
#Swift
Swift
var funcs: [() -> Int] = [] for var i = 0; i < 10; i++ { funcs.append({ i * i }) } println(funcs[3]()) // prints 100
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
#J
J
average =: +/ % #   circles =: verb define"1 'P0 P1 R' =. (j./"1)_2[\y NB. Use complex plane C =. P0 average@:, P1 BAD =: ":@:+. C SEPARATION =. P0 |@- P1 if. 0 = SEPARATION do. if. 0 = R do. 'Degenerate point at ' , BAD else. 'Any center at a distance ' , (":R) , ' from ' , BAD , ' works.' end. elseif. SEPARATION (> +:) R do. 'No solutions.' elseif. SEPARATION (= +:) R do. 'Duplicate solutions with center at ' , BAD elseif. 1 do. ORTHOGONAL_DISTANCE =. R * 1 o. _2 o. R %~ | C - P0 UNIT =: P1 *@:- P0 OFFSETS =: ORTHOGONAL_DISTANCE * UNIT * j. _1 1 C +.@:+ OFFSETS end. )   INPUT=: ".;._2]0 :0 0.1234 0.9876 0.8765 0.2345 2 0 2 0 0 1 0.1234 0.9876 0.1234 0.9876 2 0.1234 0.9876 0.8765 0.2345 0.5 0.1234 0.9876 0.1234 0.9876 0 )   ('x0 y0 x1 y1 r' ; 'center'),(;circles)"1 INPUT ┌───────────────────────────────┬────────────────────────────────────────────────────┐ │x0 y0 x1 y1 r │center │ ├───────────────────────────────┼────────────────────────────────────────────────────┤ │0.1234 0.9876 0.8765 0.2345 2 │_0.863212 _0.752112 │ │ │ 1.86311 1.97421 │ ├───────────────────────────────┼────────────────────────────────────────────────────┤ │0 2 0 0 1 │Duplicate solutions with center at 0 1 │ ├───────────────────────────────┼────────────────────────────────────────────────────┤ │0.1234 0.9876 0.1234 0.9876 2 │Any center at a distance 2 from 0.1234 0.9876 works.│ ├───────────────────────────────┼────────────────────────────────────────────────────┤ │0.1234 0.9876 0.8765 0.2345 0.5│No solutions. │ ├───────────────────────────────┼────────────────────────────────────────────────────┤ │0.1234 0.9876 0.1234 0.9876 0 │Degenerate point at 0.1234 0.9876 │ └───────────────────────────────┴────────────────────────────────────────────────────┘  
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).
#Haskell
Haskell
import Data.Array (Array, listArray, (!))   ------------------- TRADITIONAL STRINGS ------------------ ats :: Array Int (Char, String) ats = listArray (0, 9) $ zip -- 天干 tiangan – 10 heavenly stems "甲乙丙丁戊己庚辛壬癸" (words "jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi")   ads :: Array Int (String, String) ads = listArray (0, 11) $ zip -- 地支 dizhi – 12 terrestrial branches (chars "子丑寅卯辰巳午未申酉戌亥") ( words $ "zĭ chŏu yín măo chén sì " <> "wŭ wèi shēn yŏu xū hài" )   aws :: Array Int (String, String, String) aws = listArray (0, 4) $ zip3 -- 五行 wuxing – 5 elements (chars "木火土金水") (words "mù huǒ tǔ jīn shuǐ") (words "wood fire earth metal water")   axs :: Array Int (String, String, String) axs = listArray (0, 11) $ zip3 -- 十二生肖 shengxiao – 12 symbolic animals (chars "鼠牛虎兔龍蛇馬羊猴鸡狗豬") ( words $ "shǔ niú hǔ tù lóng shé " <> "mǎ yáng hóu jī gǒu zhū" ) ( words $ "rat ox tiger rabbit dragon snake " <> "horse goat monkey rooster dog pig" )   ays :: Array Int (String, String) -- 阴阳 yinyang ays = listArray (0, 1) $ zip (chars "阳阴") (words "yáng yīn")   chars :: String -> [String] chars = (flip (:) [] <$>)   -------------------- TRADITIONAL CYCLES ------------------ f生肖五行年份 y = let i年份 = y - 4 i天干 = rem i年份 10 i地支 = rem i年份 12 (h天干, p天干) = ats ! i天干 (h地支, p地支) = ads ! i地支 (h五行, p五行, e五行) = aws ! quot i天干 2 (h生肖, p生肖, e生肖) = axs ! i地支 (h阴阳, p阴阳) = ays ! rem i年份 2 in -- 汉子 Chinese characters [ [show y, h天干 : h地支, h五行, h生肖, h阴阳], -- Pinyin roman transcription [[], p天干 <> p地支, p五行, p生肖, p阴阳], -- English [ [], show (rem i年份 60 + 1) <> "/60", e五行, e生肖, [] ] ]   --------------------------- TEST ------------------------- main :: IO () main = mapM_ putStrLn $ showYear <$> [1935, 1938, 1968, 1972, 1976, 1984, 2017]   ------------------------ FORMATTING ---------------------- fieldWidths :: [[Int]] fieldWidths = [ [6, 10, 7, 8, 3], [6, 11, 8, 8, 4], [6, 11, 8, 8, 4] ]   showYear :: Int -> String showYear y = unlines $ ( \(ns, xs) -> concat $ uncurry (`justifyLeft` ' ') <$> zip ns xs ) <$> zip fieldWidths (f生肖五行年份 y) where justifyLeft n c s = take n (s <> replicate n c)