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
#Clojure
Clojure
    (dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./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
#COBOL
COBOL
identification division. program-id. check-file-exist.   environment division. configuration section. repository. function all intrinsic.   data division. working-storage section. 01 skip pic 9 value 2. 01 file-name. 05 value "/output.txt". 01 dir-name. 05 value "/docs/". 01 unusual-name. 05 value "Abdu'l-Bahá.txt".   01 test-name pic x(256).   01 file-handle usage binary-long. 01 file-info. 05 file-size pic x(8) comp-x. 05 file-date. 10 file-day pic x comp-x. 10 file-month pic x comp-x. 10 file-year pic xx comp-x. 05 file-time. 10 file-hours pic x comp-x. 10 file-minutes pic x comp-x. 10 file-seconds pic x comp-x. 10 file-hundredths pic x comp-x.   procedure division. files-main.   *> check in current working dir move file-name(skip:) to test-name perform check-file   move dir-name(skip:) to test-name perform check-file   move unusual-name to test-name perform check-file   *> check in root dir move 1 to skip move file-name(skip:) to test-name perform check-file   move dir-name(skip:) to test-name perform check-file   goback.   check-file. call "CBL_CHECK_FILE_EXIST" using test-name file-info if return-code equal zero then display test-name(1:32) ": size " file-size ", " file-year "-" file-month "-" file-day space file-hours ":" file-minutes ":" file-seconds "." file-hundredths else display "error: CBL_CHECK_FILE_EXIST " return-code space trim(test-name) end-if .   end program check-file-exist.  
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
#F.23
F#
  open System.Windows.Forms open System.Drawing open System   let sz = 300 let polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]   let bmp = new Bitmap(sz, sz) let paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)   let random = Random() let seed = Point(int (random.NextDouble() * float sz), int (random.NextDouble() * float sz)) let midpoint (p1: Point) (p2: Point) = Point((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2) let randomVertex() = polygon.[random.Next(polygon.Length)] let step p _ = paint p midpoint p (randomVertex()) Seq.init 100000 id |> Seq.fold step seed   let f = new Form() f.ClientSize <- bmp.Size f.Paint.Add (fun args -> args.Graphics.DrawImage(bmp, Point(0, 0))) f.Show()  
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.
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-} import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative   type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)}   echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask   userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name)   removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name)   addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name   broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ")   clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users   main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server  
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.
#ooRexx
ooRexx
/*REXX ---------------------------------------------------------------- * 09.04.2014 Walter Pachl the REXX solution adapted for ooRexx * which provides a function package rxMath *--------------------------------------------------------------------*/ Numeric Digits 16 Numeric Fuzz 3; pi=rxCalcpi(); a.='' a.1 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/3,16,'R')' a.2 = 'pi/4 = 2*rxCalcarctan(1/3,16,'R') + rxCalcarctan(1/7,16,'R')' a.3 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/239,16,'R')' a.4 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 2*rxCalcarctan(3/79,16,'R')' a.5 = 'pi/4 = 5*rxCalcarctan(29/278,16,'R') + 7*rxCalcarctan(3/79,16,'R')' a.6 = 'pi/4 = rxCalcarctan(1/2,16,'R') + rxCalcarctan(1/5,16,'R') + rxCalcarctan(1/8,16,'R')' a.7 = 'pi/4 = 4*rxCalcarctan(1/5,16,'R') - rxCalcarctan(1/70,16,'R') + rxCalcarctan(1/99,16,'R')' a.8 = 'pi/4 = 5*rxCalcarctan(1/7,16,'R') + 4*rxCalcarctan(1/53,16,'R') + 2*rxCalcarctan(1/4443,16,'R')' a.9 = 'pi/4 = 6*rxCalcarctan(1/8,16,'R') + 2*rxCalcarctan(1/57,16,'R') + rxCalcarctan(1/239,16,'R')' a.10 = 'pi/4 = 8*rxCalcarctan(1/10,16,'R') - rxCalcarctan(1/239,16,'R') - 4*rxCalcarctan(1/515,16,'R')' a.11 = 'pi/4 = 12*rxCalcarctan(1/18,16,'R') + 8*rxCalcarctan(1/57,16,'R') - 5*rxCalcarctan(1/239,16,'R')' a.12 = 'pi/4 = 16*rxCalcarctan(1/21,16,'R') + 3*rxCalcarctan(1/239,16,'R') + 4*rxCalcarctan(3/1042,16,'R')' a.13 = 'pi/4 = 22*rxCalcarctan(1/28,16,'R') + 2*rxCalcarctan(1/443,16,'R') - 5*rxCalcarctan(1/1393,16,'R') - 10*rxCalcarctan(1/11018,16,'R')' a.14 = 'pi/4 = 22*rxCalcarctan(1/38,16,'R') + 17*rxCalcarctan(7/601,16,'R') + 10*rxCalcarctan(7/8149,16,'R')' a.15 = 'pi/4 = 44*rxCalcarctan(1/57,16,'R') + 7*rxCalcarctan(1/239,16,'R') - 12*rxCalcarctan(1/682,16,'R') + 24*rxCalcarctan(1/12943,16,'R')' a.16 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12943,16,'R')' a.17 = 'pi/4 = 88*rxCalcarctan(1/172,16,'R') + 51*rxCalcarctan(1/239,16,'R') + 32*rxCalcarctan(1/682,16,'R') + 44*rxCalcarctan(1/5357,16,'R') + 68*rxCalcarctan(1/12944,16,'R')' do j=1 while a.j\=='' /*evaluate each of the formulas. */ interpret 'answer=' "(" a.j ")" /*the heavy lifting.*/ say right(word('bad OK',answer+1),3)": " space(a.j,0) end /*j*/ /* [?] show OK | bad, formula. */ ::requires rxmath library  
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.
#Batch_File
Batch File
  @echo off :: Supports all ASCII characters and codes from 34-126 with the exceptions of: :: 38 & :: 60 < :: 62 > :: 94 ^ :: 124 |   :_main call:_toCode a call:_toChar 97 pause>nul exit /b   :_toCode setlocal enabledelayedexpansion set codecount=32   for /l %%i in (33,1,126) do ( set /a codecount+=1 cmd /c exit %%i if %1==!=exitcodeAscii! ( echo !codecount! exit /b ) )   :_toChar setlocal cmd /c exit %1 echo %=exitcodeAscii% exit /b  
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.
#JavaScript
JavaScript
  const cholesky = function (array) { const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0)); const L = zeros.map((row, r, xL) => row.map((v, c) => { const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0); return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v; })); return L; }   let arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; console.log(cholesky(arr3)); let arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; console.log(cholesky(arr4));  
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
#jq
jq
def count(stream; cond): reduce stream as $i (0; if $i|cond then .+1 else . end);   def Months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];   # tostring def birthday: "\(Months[.month-1]) \(.day)";   # Input: a Birthday def monthUniqueIn($bds): .month as $thisMonth | count( $bds[]; .month == $thisMonth) == 1;   # Input: a Birthday def dayUniqueIn($bds): .day as $thisDay | count( $bds[]; .day == $thisDay) == 1;   # Input: a Birthday def monthWithUniqueDayIn($bds): .month as $thisMonth | any( $bds[]; $thisMonth == .month and dayUniqueIn($bds));   def choices: [ {month: 5, day: 15}, {month: 5, day: 16}, {month: 5, day: 19}, {month: 6, day: 17}, {month: 6, day: 18}, {month: 7, day: 14}, {month: 7, day: 16}, {month: 8, day: 14}, {month: 8, day: 15}, {month: 8, day: 17} ];   # Albert knows the month but doesn't know the day, # so the month can't be unique within the choices. def filter1: . as $in | map(select( monthUniqueIn($in) | not));   # Albert also knows that Bernard doesn't know the answer, # so the month can't have a unique day. def filter2: . as $in | map(select( monthWithUniqueDayIn($in) | not));   # Bernard now knows the answer, # so the day must be unique within the remaining choices. def filter3: . as $in | map(select( dayUniqueIn($in) ));   # Albert now knows the answer too. # So the month must be unique within the remaining choices. def filter4: . as $in | map(select( monthUniqueIn($in) ));   def solve: (choices | filter1 | filter2 | filter3 | filter4) as $bds | if $bds|length == 1 then "Cheryl's birthday is \($bds[0]|birthday)." else "Whoops!" end;   solve
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
#Julia
Julia
const dates = [[15, "May"], [16, "May"], [19, "May"], [17, "June"], [18, "June"], [14, "July"], [16, "July"], [14, "August"], [15, "August"], [17, "August"]]   uniqueday(parr) = filter(x -> count(y -> y[1] == x[1], parr) == 1, parr)   # At the start, they come to know that they have no unique day of month to identify. const f1 = filter(m -> !(m[2] in [d[2] for d in uniqueday(dates)]), dates)   # After cutting months with unique dates, get months remaining that now have a unique date. const f2 = uniqueday(f1)   # filter for those of the finally remaining months that have only one date left. const bday = filter(x -> count(m -> m[2] == x[2], f2) == 1, f2)[]   println("Cheryl's birthday is $(bday[2]) $(bday[1]).")  
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.
#Ruby
Ruby
require 'socket'   # A Workshop runs all of its workers, then collects their results. Use # Workshop#add to add workers and Workshop#work to run them. # # This implementation forks some processes to run the workers in # parallel. Ruby must provide Kernel#fork and 'socket' library must # provide UNIXSocket. # # Why processes and not threads? C Ruby still has a Global VM Lock, # where only one thread can hold the lock. One platform, OpenBSD, still # has userspace threads, with all threads on one cpu core. Multiple # processes will not compete for a single Global VM Lock and can run # on multiple cpu cores. class Workshop # Creates a Workshop. def initialize @sockets = {} end   # Adds a worker to this Workshop. Returns a worker id _wid_ for this # worker. The worker is a block that takes some _args_ and returns # some value. Workshop#work will run the block. # # This implementation forks a process for the worker. This process # will use Marshal with UNIXSocket to receive the _args_ and to send # the return value. The _wid_ is a process id. The worker also # inherits _IO_ objects, which might be a problem if the worker holds # open a pipe or socket, and the other end never reads EOF. def add child, parent = UNIXSocket.pair   wid = fork do # I am the child. child.close @sockets.each_value { |sibling| sibling.close }   # Prevent that all the children print their backtraces (to a mess # of mixed lines) when user presses Control-C. Signal.trap("INT") { exit! }   loop do # Wait for a command. begin command, args = Marshal.load(parent) rescue EOFError # Parent probably died. break end   case command when :work # Do work. Send result to parent. result = yield *args Marshal.dump(result, parent) when :remove break else fail "bad command from workshop" end end end   # I am the parent. parent.close @sockets[wid] = child wid end   # Runs all of the workers, and collects the results in a Hash. Passes # the same _args_ to each of the workers. Returns a Hash that pairs # _wid_ => _result_, where _wid_ is the worker id and _result_ is the # return value from the worker. # # This implementation runs the workers in parallel, and waits until # _all_ of the workers finish their results. Workshop provides no way # to start the work without waiting for the work to finish. If a # worker dies (for example, by raising an Exception), then # Workshop#work raises a RuntimeError. def work(*args) message = [:work, args] @sockets.each_pair do |wid, child| Marshal.dump(message, child) end   # Checkpoint! Wait for all workers to finish. result = {} @sockets.each_pair do |wid, child| begin # This waits until the child finishes a result. result[wid] = Marshal.load(child) rescue EOFError fail "Worker #{wid} died" end end result end   # Removes a worker from the Workshop, who has a worker id _wid_. # If there is no such worker, raises ArgumentError. # # This implementation kills and reaps the process for the worker. def remove(wid) unless child = @sockets.delete(wid) raise ArgumentError, "No worker #{wid}" else Marshal.dump([:remove, nil], child) child.close Process.wait(wid) end end end       # First create a Workshop. require 'pp' shop = Workshop.new wids = []   # Our workers must not use the same random numbers after the fork. @fixed_rand = false def fix_rand unless @fixed_rand; srand; @fixed_rand = true; end end   # Start with some workers. 6.times do wids << shop.add do |i| # This worker slowly calculates a Fibonacci number. fix_rand f = proc { |n| if n < 2 then n else f[n - 1] + f[n - 2] end } [i, f[25 + rand(10)]] end end   6.times do |i| # Do one cycle of work, and print the result. pp shop.work(i)   # Remove a worker. victim = rand(wids.length) shop.remove wids[victim] wids.slice! victim   # Add another worker. wids << shop.add do |j| # This worker slowly calculates a number from # the sequence 0, 1, 2, 3, 6, 11, 20, 37, 68, 125, ... fix_rand f = proc { |n| if n < 3 then n else f[n - 1] + f[n - 2] + f[n - 3] end } [j, i, f[20 + rand(10)]] end end   # Remove all workers. wids.each { |wid| shop.remove wid } pp shop.work(6)
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
#Kotlin
Kotlin
import java.util.PriorityQueue   fun main(args: Array<String>) { // generic array val ga = arrayOf(1, 2, 3) println(ga.joinToString(prefix = "[", postfix = "]"))   // specialized array (one for each primitive type) val da = doubleArrayOf(4.0, 5.0, 6.0) println(da.joinToString(prefix = "[", postfix = "]"))   // immutable list val li = listOf<Byte>(7, 8, 9) println(li)   // mutable list val ml = mutableListOf<Short>() ml.add(10); ml.add(11); ml.add(12) println(ml)   // immutable map val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99) println(hm)   // mutable map val mm = mutableMapOf<Char, Int>() mm.put('d', 100); mm.put('e', 101); mm.put('f', 102) println(mm)   // immutable set (duplicates not allowed) val se = setOf(1, 2, 3) println(se)   // mutable set (duplicates not allowed) val ms = mutableSetOf<Long>() ms.add(4L); ms.add(5L); ms.add(6L) println(ms)   // priority queue (imported from Java) val pq = PriorityQueue<String>() pq.add("First"); pq.add("Second"); pq.add("Third") println(pq) }
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
#Pascal
Pascal
Program Combinations;   const m_max = 3; n_max = 5; var combination: array [0..m_max] of integer;   procedure generate(m: integer); var n, i: integer; begin if (m > m_max) then begin for i := 1 to m_max do write (combination[i], ' '); writeln; end else for n := 1 to n_max do if ((m = 1) or (n > combination[m-1])) then begin combination[m] := n; generate(m + 1); end; end;   begin generate(1); end.
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.
#Sather
Sather
if EXPR then -- CODE elsif EXPR then -- CODE else -- CODE end;
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}}} .
#Groovy
Groovy
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] }   int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod }   private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1   if (b == 1) { return 1 }   while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx }   if (x1 < 0) { x1 += b0 }   return x1 }   static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(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.
#Picat
Picat
  table chowla(1) = 0. chowla(2) = 0. chowla(3) = 0. chowla(N) = C, N>3 => Max = floor(sqrt(N)), Sum = 0, foreach (X in 2..Max, N mod X == 0) Y := N div X, Sum := Sum + X + Y end, if (N == Max * Max) then Sum := Sum - Max end, C = Sum.   main => foreach (I in 1..37) printf("chowla(%d) = %d\n", I, chowla(I)) end, Ranges = {100, 1000, 10000, 100000, 1000000, 10000000}, foreach (Range in Ranges) Count = 0, foreach (I in 2..Range) if (chowla(I) == 0) then Count := Count + 1 end end, printf("There are %d primes less than %d.\n", Count, Range) end, Limit = 35000000, Count = 0, foreach (I in 2..Limit) if (chowla(I) == I-1) then printf("%d is a perfect number\n", I), Count := Count + 1 end end, printf("There are %d perfect numbers less than %d.\n", Count, Limit).  
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.
#PicoLisp
PicoLisp
(de accu1 (Var Key) (if (assoc Key (val Var)) (con @ (inc (cdr @))) (push Var (cons Key 1)) ) Key ) (de factor (N) (let (R NIL D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N) ) (while (>= M D) (if (=0 (% N D)) (setq M (sqrt (setq N (/ N (accu1 'R D)))) ) (inc 'D (pop 'L)) ) ) (accu1 'R N) (mapcar '((L) (make (for N (cdr L) (link (** (car L) N)) ) ) ) R ) ) ) (de chowla (N) (let F (factor N) (- (sum prog (make (link 1) (mapc '((A) (chain (mapcan '((B) (mapcar '((C) (* C B)) (made)) ) A ) ) ) F ) ) ) N 1 ) ) ) (de prime (N) (and (> N 1) (=0 (chowla N))) ) (de perfect (N) (and (> N 1) (= (chowla N) (dec N))) ) (de countP (N) (let C 0 (for I N (and (prime I) (inc 'C)) ) C ) ) (de listP (N) (make (for I N (and (perfect I) (link I)) ) ) ) (for I 37 (prinl "chowla(" I ") = " (chowla I)) ) (prinl "Count of primes up to 100 = " (countP 100)) (prinl "Count of primes up to 1000 = " (countP 1000)) (prinl "Count of primes up to 10000 = " (countP 10000)) (prinl "Count of primes up to 100000 = " (countP 100000)) (prinl "Count of primes up to 1000000 = " (countP 1000000)) (prinl "Count of primes up to 10000000 = " (countP 10000000)) (println (listP 35000000))
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Wren
Wren
class Church { static zero { Fn.new { Fn.new { |x| x } } }   static succ(c) { Fn.new { |f| Fn.new { |x| f.call(c.call(f).call(x)) } } }   static add(c, d) { Fn.new { |f| Fn.new { |x| c.call(f).call(d.call(f).call(x)) } } }   static mul(c, d) { Fn.new { |f| c.call(d.call(f)) } }   static pow(c, e) { e.call(c) }   static fromInt(n) { var ret = zero if (n > 0) for (i in 1..n) ret = succ(ret) return ret }   static toInt(c) { c.call(Fn.new { |x| x + 1 }).call(0) } }   var three = Church.succ(Church.succ(Church.succ(Church.zero))) var four = Church.succ(three)   System.print("three -> %(Church.toInt(three))") System.print("four -> %(Church.toInt(four))") System.print("three + four -> %(Church.toInt(Church.add(three, four)))") System.print("three * four -> %(Church.toInt(Church.mul(three, four)))") System.print("three ^ four -> %(Church.toInt(Church.pow(three, four)))") System.print("four ^ three -> %(Church.toInt(Church.pow(four, three)))")
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Lasso
Lasso
  define mytype => type { data public id::integer = 0, public val::string = '', public rand::integer = 0   public onCreate() => { // "onCreate" runs when instance created, populates .rand .rand = math_random(50,1) } public asString() => { return 'has a value of: "'+.val+'" and a rand number of "'+.rand+'"' }   }   local(x = mytype) #x->val = '99 Bottles of beer' #x->asString // outputs 'has a value of: "99 Bottles of beer" and a rand number of "48"'
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.
#LFE
LFE
  (defmodule simple-object (export all))   (defun fish-class (species) " This is the constructor used internally, once the children and fish id are known. " (let ((habitat '"water")) (lambda (method-name) (case method-name ('habitat (lambda (self) habitat)) ('species (lambda (self) species))))))   (defun get-method (object method-name) " This is a generic function, used to call into the given object (class instance). " (funcall object method-name))   ; define object methods (defun get-habitat (object) "Get a variable set in the class." (funcall (get-method object 'habitat) object))   (defun get-species (object) "Get a variable passed when constructing the object." (funcall (get-method object 'species) object))  
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)
#Objective-C
Objective-C
    type point = { x : float; y : float }     let cmpPointX (a : point) (b : point) = compare a.x b.x let cmpPointY (a : point) (b : point) = compare a.y b.y     let distSqrd (seg : (point * point) option) = match seg with | None -> max_float | Some(line) -> let a = fst line in let b = snd line in   let dx = a.x -. b.x in let dy = a.y -. b.y in   dx*.dx +. dy*.dy     let dist seg = sqrt (distSqrd seg)     let shortest l1 l2 = if distSqrd l1 < distSqrd l2 then l1 else l2     let halve l = let n = List.length l in BatList.split_at (n/2) l     let rec closestBoundY from maxY (ptsByY : point list) = match ptsByY with | [] -> None | hd :: tl -> if hd.y > maxY then None else let toHd = Some(from, hd) in let bestToRest = closestBoundY from maxY tl in shortest toHd bestToRest     let rec closestInRange ptsByY maxDy = match ptsByY with | [] -> None | hd :: tl -> let fromHd = closestBoundY hd (hd.y +. maxDy) tl in let fromRest = closestInRange tl maxDy in shortest fromHd fromRest     let rec closestPairByX (ptsByX : point list) = if List.length ptsByX < 2 then None else let (left, right) = halve ptsByX in let leftResult = closestPairByX left in let rightResult = closestPairByX right in   let bestInHalf = shortest leftResult rightResult in let bestLength = dist bestInHalf in   let divideX = (List.hd right).x in let inBand = List.filter(fun(p) -> abs_float(p.x -. divideX) < bestLength) ptsByX in   let byY = List.sort cmpPointY inBand in let bestCross = closestInRange byY bestLength in shortest bestInHalf bestCross     let closestPair pts = let ptsByX = List.sort cmpPointX pts in closestPairByX ptsByX     let parsePoint str = let sep = Str.regexp_string "," in let tokens = Str.split sep str in let xStr = List.nth tokens 0 in let yStr = List.nth tokens 1 in   let xVal = (float_of_string xStr) in let yVal = (float_of_string yStr) in   { x = xVal; y = yVal }     let loadPoints filename = let ic = open_in filename in let result = ref [] in try while true do let s = input_line ic in if s <> "" then let p = parsePoint s in result := p :: !result; done; !result with End_of_file -> close_in ic; !result ;;   let loaded = (loadPoints "Points.txt") in let start = Sys.time() in let c = closestPair loaded in let taken = Sys.time() -. start in Printf.printf "Took %f [s]\n" taken;   match c with | None -> Printf.printf "No closest pair\n" | Some(seg) -> let a = fst seg in let b = snd seg in   Printf.printf "(%f, %f) (%f, %f) Dist %f\n" a.x a.y b.x b.y (dist c)    
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
#Tcl
Tcl
package require Tcl 8.6; # Just for tailcall command # Builds a value-capturing closure; does NOT couple variables proc closure {script} { set valuemap {} foreach v [uplevel 1 {info vars}] { lappend valuemap [list $v [uplevel 1 [list set $v]]] } set body [list $valuemap $script [uplevel 1 {namespace current}]] # Wrap, to stop untoward argument passing return [list apply [list {} [list tailcall apply $body]]] # A version of the previous line compatible with Tcl 8.5 would be this # code, but the closure generated is more fragile: ### return [list apply $body] }   # Simple helper, to avoid capturing unwanted variable proc collectFor {var from to body} { upvar 1 $var v set result {} for {set v $from} {$v < $to} {incr v} {lappend result [uplevel 1 $body]} return $result } # Build a list of closures proc buildList {} { collectFor i 0 10 { closure { # This is the body of the closure return [expr $i*$i] } } } set theClosures [buildList] foreach i {a b c d e} {# Do 5 times; demonstrates no variable leakage set idx [expr {int(rand()*9)}]; # pick random int from [0..9) puts $idx=>[{*}[lindex $theClosures $idx]] }
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
#Java
Java
import java.util.Objects;   public class Circles { private static class Point { private final double x, y;   public Point(Double x, Double y) { this.x = x; this.y = y; }   public double distanceFrom(Point other) { double dx = x - other.x; double dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); }   @Override public 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 public 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 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn"); if (r == 0.0) return new Point[]{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 new Point[]{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[]{ new Point(center.x - dy, center.y + dx), new Point(center.x + dy, center.y - dx) }; }   public static void main(String[] args) { Point[] p = new Point[]{ 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 = new Point[][]{ {p[0], p[1]}, {p[2], p[3]}, {p[0], p[0]}, {p[0], p[1]}, {p[0], p[0]}, }; double[] radii = new double[]{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]; System.out.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)) { System.out.printf("there is just one circle with center at %s\n", c1); } else { System.out.printf("there are two circles with centers at %s and %s\n", c1, c2); } } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); } System.out.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).
#J
J
ELEMENTS=: _4 |. 2 # ;:'Wood Fire Earth Metal Water' YEARS=: 1935 1938 1968 1972 1976 2017   ANIMALS=: _4 |. ;:'Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig' YINYANG=: ;:'yang yin'   cz=: (|~ #)~ { [   ANIMALS cz YEARS ┌───┬─────┬──────┬───┬──────┬───────┐ │Pig│Tiger│Monkey│Rat│Dragon│Rooster│ └───┴─────┴──────┴───┴──────┴───────┘   YINYANG cz YEARS ┌───┬────┬────┬────┬────┬───┐ │yin│yang│yang│yang│yang│yin│ └───┴────┴────┴────┴────┴───┘   chinese_zodiac =: 3 : ';:inv(<":y),(ELEMENTS cz y),(ANIMALS cz y),(<''(''),(YINYANG cz y),(<'')'')'   chinese_zodiac&>YEARS 1935 Wood Pig ( yin ) 1938 Earth Tiger ( yang ) 1968 Earth Monkey ( yang ) 1972 Water Rat ( yang ) 1976 Fire Dragon ( yang ) 2017 Fire Rooster ( yin )     'CELESTIAL TERRESTRIAL'=:7&u:&.>{&a.&.> 16be7 16b94 16bb2 16be4 16bb9 16b99 16be4 16bb8 16b99 16be4 16bb8 16b81 16be6 16b88 16b8a 16be5 16bb7 16bb1 16be5 16bba 16b9a 16be8 16bbe 16b9b 16be5 16ba3 16bac 16be7 16b99 16bb8; 16be5 16bad 16b90 16be4 16bb8 16b91 16be5 16baf 16b85 16be5 16b8d 16baf 16be8 16bbe 16bb0 16be5 16bb7 16bb3 16be5 16b8d 16b88 16be6 16b9c 16baa 16be7 16b94 16bb3 16be9 16b85 16b89 16be6 16b88 16b8c 16be4 16bba 16ba5   ANIMALS=: ;/ _4 |. TERRESTRIAL ELEMENTS=: ;/ _4 |. CELESTIAL   chinese_zodiac&>YEARS 1935 乙 亥 ( yin ) 1938 戊 寅 ( yang ) 1968 戊 申 ( yang ) 1972 壬 子 ( yang ) 1976 丙 辰 ( yang ) 2017 丁 酉 ( yin )  
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
#CoffeeScript
CoffeeScript
  fs = require 'fs' path = require 'path'   root = path.resolve '/' current_dir = __dirname filename = 'input.txt' dirname = 'docs'   local_file = path.join current_dir, filename local_dir = path.join current_dir, dirname   root_file = path.join root, filename root_dir = path.join root, dirname   for p in [ local_file, local_dir, root_file, root_dir ] then do ( p ) -> fs.exists p, ( p_exists ) -> unless p_exists console.log "#{ p } does not exist." else then fs.stat p, ( error, stat ) -> console.log "#{ p } exists and is a #{ if stat.isFile() then 'file' else then 'directory' }."      
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
#Common_Lisp
Common Lisp
(if (probe-file (make-pathname :name "input.txt")) (print "rel file exists")) (if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt")) (print "abs file exists"))   (if (directory (make-pathname :directory '(:relative "docs"))) (print "rel directory exists") (print "rel directory is not known to exist")) (if (directory (make-pathname :directory '(:absolute "docs"))) (print "abs directory exists") (print "abs directory is not known to exist"))
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
#Fortran
Fortran
  PROGRAM CHAOS IMPLICIT NONE REAL, DIMENSION(3):: KA, KN ! Koordinates old/new REAL, DIMENSION(3):: DA, DB, DC ! Triangle INTEGER:: I, Z INTEGER, PARAMETER:: UT = 17 ! Define corners of triangle DA = (/ 0., 0., 0. /) DB = (/ 600., 0., 0. /) DC = (/ 500., 0., 400. /) ! Define starting point KA = (/ 500., 0., 100. /) OPEN (UNIT = UT, FILE = 'aus.csv') DO I=1, 1000000 Z = ZAHL() WRITE (UT, '(3(F12.6, ";"))') KA SELECT CASE (Z) CASE (1) CALL MITTELP(KA, DA, KN) CASE (2) CALL MITTELP(KA, DB, KN) CASE (3) CALL MITTELP(KA, DC, KN) END SELECT KA = KN END DO CLOSE (UT) CONTAINS ! Calculates center of two points SUBROUTINE MITTELP(P1, P2, MP) REAL, INTENT(IN), DIMENSION(3):: P1, P2 REAL, INTENT(OUT), DIMENSION(3):: MP MP = (P1 + P2) / 2. END SUBROUTINE MITTELP ! Returns random number INTEGER FUNCTION ZAHL() REAL:: ZZ CALL RANDOM_NUMBER(ZZ) ZZ = ZZ * 3. ZAHL = FLOOR(ZZ) + 1 IF (ZAHL .GT. 3) ZAHL = 3 END FUNCTION ZAHL END PROGRAM CHAOS  
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.
#Icon_and_Unicon
Icon and Unicon
global mlck, nCons, cons   procedure main() mlck := mutex() nCons := 0 cons := mutex(set()) while f := open(":12321","na") do { handle_client(f) critical mlck: if nCons <= 0 then close(f) } end   procedure handle_client(f) critical mlck: nCons +:= 1 thread { select(f,1000) & { writes(f, "Name? ") nick := (read(f) ? tab(upto('\n\r'))) every write(!cons, nick," has joined.") insert(cons, f) while s := read(f) do every write(!cons, nick,": ",s) } delete(cons, f) every write(!cons, nick," has left.") critical mlck: nCons -:= 1 } 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.
#PARI.2FGP
PARI/GP
tanEval(coef, f)={ if (coef <= 1, return(if(coef<1,-tanEval(-coef, f),f))); my(a=tanEval(coef\2, f), b=tanEval(coef-coef\2, f)); (a + b)/(1 - a*b) }; tans(xs)={ if (#xs == 1, return(tanEval(xs[1][1], xs[1][2]))); my(a=tans(xs[1..#xs\2]),b=tans(xs[#xs\2+1..#xs])); (a + b)/(1 - a*b) }; test(v)={ my(t=tans(v)); if(t==1,print("OK"),print("Error: "v)) }; test([[1,1/2],[1,1/3]]); test([[2,1/3],[1,1/7]]); test([[4,1/5],[-1,1/239]]); test([[5,1/7],[2,3/79]]); test([[5,29/278],[7,3/79]]); test([[1,1/2],[1,1/5],[1,1/8]]); test([[4,1/5],[-1,1/70],[1,1/99]]); test([[5,1/7],[4,1/53],[2,1/4443]]); test([[6,1/8],[2,1/57],[1,1/239]]); test([[8,1/10],[-1,1/239],[-4,1/515]]); test([[12,1/18],[8,1/57],[-5,1/239]]); test([[16,1/21],[3,1/239],[4,3/1042]]); test([[22,1/28],[2,1/443],[-5,1/1393],[-10,1/11018]]); test([[22,1/38],[17,7/601],[10,7/8149]]); test([[44,1/57],[7,1/239],[-12,1/682],[24,1/12943]]); test([[88,1/172],[51,1/239],[32,1/682],[44,1/5357],[68,1/12943]]); test([[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.
#BBC_BASIC
BBC BASIC
charCode = 97 char$ = "a" PRINT CHR$(charCode) : REM prints a PRINT ASC(char$) : REM 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.
#Befunge
Befunge
"a". 99*44*+, @
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.
#jq
jq
# Create an m x n matrix def matrix(m; n; init): if m == 0 then [] elif m == 1 then [range(0; n)] | map(init) elif m > 0 then matrix(1; n; init) as $row | [range(0; m)] | map( $row ) else error("matrix\(m);_;_) invalid") end ;   # Print a matrix neatly, each cell ideally occupying n spaces, # but without truncation def neatly(n): def right: tostring | ( " " * (n-length) + .); . as $in | length as $length | reduce range (0; $length) as $i (""; . + reduce range(0; $length) as $j (""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;   def is_square: type == "array" and (map(type == "array") | all) and length == 0 or ( (.[0]|length) as $l | map(length == $l) | all) ;   # This implementation of is_symmetric/0 uses a helper function that circumvents # limitations of jq 1.4: def is_symmetric: # [matrix, i,j, len] def test: if .[1] > .[3] then true elif .[1] == .[2] then [ .[0], .[1] + 1, 0, .[3]] | test elif .[0][.[1]][.[2]] == .[0][.[2]][.[1]] then [ .[0], .[1], .[2]+1, .[3]] | test else false end; if is_square|not then false else [ ., 0, 0, length ] | test end ;  
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.
#Julia
Julia
  a = [25 15 5; 15 18 0; -5 0 11] b = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106]   println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))  
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Kotlin
Kotlin
// Version 1.2.71   val months = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" )   class Birthday(val month: Int, val day: Int) { public override fun toString() = "${months[month - 1]} $day"   public fun monthUniqueIn(bds: List<Birthday>): Boolean { return bds.count { this.month == it.month } == 1 }   public fun dayUniqueIn(bds: List<Birthday>): Boolean { return bds.count { this.day == it.day } == 1 }   public fun monthWithUniqueDayIn(bds: List<Birthday>): Boolean { return bds.any { (this.month == it.month) && it.dayUniqueIn(bds) } } }   fun main(args: Array<String>) { val choices = listOf( Birthday(5, 15), Birthday(5, 16), Birthday(5, 19), Birthday(6, 17), Birthday(6, 18), Birthday(7, 14), Birthday(7, 16), Birthday(8, 14), Birthday(8, 15), Birthday(8, 17) )   // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. var filtered = choices.filterNot { it.monthUniqueIn(choices) }   // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. filtered = filtered.filterNot { it.monthWithUniqueDayIn(filtered) }   // Bernard now knows the answer. // So the day must be unique within the remaining choices. filtered = filtered.filter { it.dayUniqueIn(filtered) }   // Albert now knows the answer too. // So the month must be unique within the remaining choices. filtered = filtered.filter { it.monthUniqueIn(filtered) }   if (filtered.size == 1) println("Cheryl's birthday is ${filtered[0]}") else println("Something went wrong!") }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Rust
Rust
  //! We implement this task using Rust's Barriers. Barriers are simply thread synchronization //! points--if a task waits at a barrier, it will not continue until the number of tasks for which //! the variable was initialized are also waiting at the barrier, at which point all of them will //! stop waiting. This can be used to allow threads to do asynchronous work and guarantee //! properties at checkpoints.   use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::channel; use std::sync::{Arc, Barrier}; use std::thread::spawn;   use array_init::array_init;   pub fn checkpoint() { const NUM_TASKS: usize = 10; const NUM_ITERATIONS: u8 = 10;   let barrier = Barrier::new(NUM_TASKS); let events: [AtomicBool; NUM_TASKS] = array_init(|_| AtomicBool::new(false));   // Arc for sharing between tasks let arc = Arc::new((barrier, events)); // Channel for communicating when tasks are done let (tx, rx) = channel(); for i in 0..NUM_TASKS { let arc = Arc::clone(&arc); let tx = tx.clone(); // Spawn a new worker spawn(move || { let (ref barrier, ref events) = *arc; // Assign an event to this task let event = &events[i]; // Start processing events for _ in 0..NUM_ITERATIONS { // Between checkpoints 4 and 1, turn this task's event on. event.store(true, Ordering::Release); // Checkpoint 1 barrier.wait(); // Between checkpoints 1 and 2, all events are on. assert!(events.iter().all(|e| e.load(Ordering::Acquire))); // Checkpoint 2 barrier.wait(); // Between checkpoints 2 and 3, turn this task's event off. event.store(false, Ordering::Release); // Checkpoint 3 barrier.wait(); // Between checkpoints 3 and 4, all events are off. assert!(events.iter().all(|e| !e.load(Ordering::Acquire))); // Checkpoint 4 barrier.wait(); } // Finish processing events. tx.send(()).unwrap(); }); } drop(tx); // The main thread will not exit until all tasks have exited. for _ in 0..NUM_TASKS { rx.recv().unwrap(); } }   fn main() { checkpoint(); }  
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.
#Scala
Scala
import java.util.{Random, Scanner}   object CheckpointSync extends App { val in = new Scanner(System.in)   /* * Informs that workers started working on the task and * starts running threads. Prior to proceeding with next * task syncs using static Worker.checkpoint() method. */ private def runTasks(nTasks: Int): Unit = {   for (i <- 0 until nTasks) { println("Starting task number " + (i + 1) + ".") runThreads() Worker.checkpoint() } }   /* * Creates a thread for each worker and runs it. */ private def runThreads(): Unit = for (i <- 0 until Worker.nWorkers) new Thread(new Worker(i + 1)).start()   class Worker(/* inner class instance variables */ var threadID: Int) extends Runnable { override def run(): Unit = { work() }   /* * Notifies that thread started running for 100 to 1000 msec. * Once finished increments static counter 'nFinished' * that counts number of workers finished their work. */ private def work(): Unit = { try { val workTime = Worker.rgen.nextInt(900) + 100 println("Worker " + threadID + " will work for " + workTime + " msec.") Thread.sleep(workTime) //work for 'workTime'   Worker.nFinished += 1 //increases work finished counter   println("Worker " + threadID + " is ready") } catch { case e: InterruptedException => System.err.println("Error: thread execution interrupted") e.printStackTrace() } } }   /* * Worker inner static class. */ object Worker { private val rgen = new Random var nWorkers = 0 private var nFinished = 0   /* * Used to synchronize Worker threads using 'nFinished' static integer. * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. * Once they are equal resets 'nFinished' counter. */ def checkpoint(): Unit = { while (nFinished != nWorkers) try Thread.sleep(10) catch { case e: InterruptedException => System.err.println("Error: thread execution interrupted") e.printStackTrace() } nFinished = 0 } }   print("Enter number of workers to use: ") Worker.nWorkers = in.nextInt print("Enter number of tasks to complete:") runTasks(in.nextInt)   }
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
#Lingo
Lingo
-- list stuff l = [1, 2] l.add(3) l.add(4) put l -- [1, 2, 3, 4]   -- property list stuff pl = [#foo: 1, #bar: 2] pl[#foobar] = 3 pl["barfoo"] = 4 put pl -- [#foo: 1, #bar: 2, #foobar: 3, "barfoo": 4]
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
#Perl
Perl
use ntheory qw/forcomb/; forcomb { print "@_\n" } 5,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.
#Scala
Scala
if (n == 12) "twelve" else "not twelve"   today match { case Monday => Compute_Starting_Balance; case Friday => Compute_Ending_Balance; case Tuesday => Accumulate_Sales case _ => {} }
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}}} .
#Haskell
Haskell
import Control.Monad (zipWithM)   egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b   modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b   chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii   main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 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.
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL #COMPILER PBCC 6   FUNCTION chowla(BYVAL n AS LONG) AS LONG REGISTER i AS LONG, j AS LONG LOCAL r AS LONG i = 2 DO WHILE i * i <= n j = n \ i IF n MOD i = 0 THEN r += i IF i <> j THEN r += j END IF END IF INCR i LOOP FUNCTION = r END FUNCTION   FUNCTION chowla1(BYVAL n AS QUAD) AS QUAD LOCAL i, j, r AS QUAD i = 2 DO WHILE i * i <= n j = n \ i IF n MOD i = 0 THEN r += i IF i <> j THEN r += j END IF END IF INCR i LOOP FUNCTION = r END FUNCTION   SUB sieve(BYVAL limit AS LONG, BYREF c() AS INTEGER) LOCAL i, j AS LONG REDIM c(limit - 1) i = 3 DO WHILE i * 3 < limit IF NOT c(i) THEN IF chowla(i) = 0 THEN j = 3 * i DO WHILE j < limit c(j) = -1 j += 2 * i LOOP END IF END IF i += 2 LOOP END SUB   FUNCTION PBMAIN () AS LONG LOCAL i, count, limit, power AS LONG LOCAL c() AS INTEGER LOCAL s AS STRING LOCAL s30 AS STRING * 30 LOCAL p, k, kk, r, ql AS QUAD FOR i = 1 TO 37 s = "chowla(" & TRIM$(STR$(i)) & ") = " & TRIM$(STR$(chowla(i))) CON.PRINT s NEXT i count = 1 limit = 10000000 power = 100 CALL sieve(limit, c()) FOR i = 3 TO limit - 1 STEP 2 IF ISFALSE c(i) THEN count += 1 IF i = power - 1 THEN RSET s30 = FORMAT$(power, "#,##0") s = "Count of primes up to " & s30 & " =" & STR$(count) CON.PRINT s power *= 10 END IF NEXT i   ql = 2 ^ 61 k = 2: kk = 3 RESET count DO p = k * kk : IF p > ql THEN EXIT DO IF chowla1(p) = p - 1 THEN RSET s30 = FORMAT$(p, "#,##0") s = s30 & " is a number that is perfect" CON.PRINT s count += 1 END IF k = kk + 1 : kk += k LOOP s = "There are" & STR$(count) & " perfect numbers <= " & FORMAT$(ql, "#,##0") CON.PRINT s   CON.PRINT "press any key to exit program" CON.WAITKEY$ END FUNCTION
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.
#Prolog
Prolog
  chowla(1, 0). chowla(2, 0). chowla(N, C) :- N > 2, Max is floor(sqrt(N)), findall(X, (between(2, Max, X), N mod X =:= 0), Xs), findall(Y, (member(X1, Xs), Y is N div X1, Y \= Max), Ys), !, sum_list(Xs, S1), sum_list(Ys, S2), C is S1 + S2.   prime_count(Upper, Upper, Count, Count) :- !.   prime_count(Lower, Upper, Add, Count) :- chowla(Lower, 0), !, Lower1 is Lower + 1, Add1 is Add + 1, prime_count(Lower1, Upper, Add1, Count).   prime_count(Lower, Upper, Add, Count) :- Lower1 is Lower + 1, prime_count(Lower1, Upper, Add, Count).   perfect_numbers(Upper, Upper, AccNums, Nums) :- !, reverse(AccNums, Nums).   perfect_numbers(Lower, Upper, AccNums, Nums) :- Perfect is Lower - 1, chowla(Lower, Perfect), !, Lower1 is Lower + 1, AccNums1 = [Lower|AccNums], perfect_numbers(Lower1, Upper, AccNums1, Nums).   perfect_numbers(Lower, Upper, AccNums, Nums) :- Lower1 is Lower + 1, perfect_numbers(Lower1, Upper, AccNums, Nums).   main :- % Chowla numbers forall(between(1, 37, N), ( chowla(N, C), format('chowla(~D) = ~D\n', [N, C]) )),   % Prime numbers Ranges = [100, 1000, 10000, 100000, 1000000, 10000000], forall(member(Range, Ranges), ( prime_count(2, Range, 0, PrimeCount), format('There are ~D primes less than ~D.\n', [PrimeCount, Range]) )),   % Perfect numbers Limit = 35000000, perfect_numbers(2, Limit, [], Nums), forall(member(Perfect, Nums), ( format('~D is a perfect number.\n', [Perfect]) )), length(Nums, PerfectCount), format('There are ~D perfect numbers < ~D.\n', [PerfectCount, 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.
#zkl
zkl
class Church{ // kinda heavy, just an int + fcn churchAdd(ca,cb) would also work fcn init(N){ var n=N; } // Church Zero is Church(0) fcn toInt(f,x){ do(n){ x=f(x) } x } // c(3)(f,x) --> f(f(f(x))) fcn succ{ self(n+1) } fcn __opAdd(c){ self(n+c.n) } fcn __opMul(c){ self(n*c.n) } fcn pow(c) { self(n.pow(c.n)) } fcn toString{ String("Church(",n,")") } }
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.
#Lingo
Lingo
---------------------------------------- -- @desc Class "MyClass" -- @file parent script "MyClass" ----------------------------------------   -- instance variable property _myvar   -- constructor on new (me) me._myvar = 23 return me end   -- a method on doubleAndPrint (me) me._myvar = me._myvar * 2 put me._myvar 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.
#Lisaac
Lisaac
Section Header   + name := SAMPLE;   Section Inherit   - parent : OBJECT := OBJECT;   Section Private   + variable : INTEGER <- 0;   Section Public   - some_method <- ( variable := 1; );   - main <- ( + sample : SAMPLE;   sample := SAMPLE.clone; sample.some_method; );
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)
#OCaml
OCaml
    type point = { x : float; y : float }     let cmpPointX (a : point) (b : point) = compare a.x b.x let cmpPointY (a : point) (b : point) = compare a.y b.y     let distSqrd (seg : (point * point) option) = match seg with | None -> max_float | Some(line) -> let a = fst line in let b = snd line in   let dx = a.x -. b.x in let dy = a.y -. b.y in   dx*.dx +. dy*.dy     let dist seg = sqrt (distSqrd seg)     let shortest l1 l2 = if distSqrd l1 < distSqrd l2 then l1 else l2     let halve l = let n = List.length l in BatList.split_at (n/2) l     let rec closestBoundY from maxY (ptsByY : point list) = match ptsByY with | [] -> None | hd :: tl -> if hd.y > maxY then None else let toHd = Some(from, hd) in let bestToRest = closestBoundY from maxY tl in shortest toHd bestToRest     let rec closestInRange ptsByY maxDy = match ptsByY with | [] -> None | hd :: tl -> let fromHd = closestBoundY hd (hd.y +. maxDy) tl in let fromRest = closestInRange tl maxDy in shortest fromHd fromRest     let rec closestPairByX (ptsByX : point list) = if List.length ptsByX < 2 then None else let (left, right) = halve ptsByX in let leftResult = closestPairByX left in let rightResult = closestPairByX right in   let bestInHalf = shortest leftResult rightResult in let bestLength = dist bestInHalf in   let divideX = (List.hd right).x in let inBand = List.filter(fun(p) -> abs_float(p.x -. divideX) < bestLength) ptsByX in   let byY = List.sort cmpPointY inBand in let bestCross = closestInRange byY bestLength in shortest bestInHalf bestCross     let closestPair pts = let ptsByX = List.sort cmpPointX pts in closestPairByX ptsByX     let parsePoint str = let sep = Str.regexp_string "," in let tokens = Str.split sep str in let xStr = List.nth tokens 0 in let yStr = List.nth tokens 1 in   let xVal = (float_of_string xStr) in let yVal = (float_of_string yStr) in   { x = xVal; y = yVal }     let loadPoints filename = let ic = open_in filename in let result = ref [] in try while true do let s = input_line ic in if s <> "" then let p = parsePoint s in result := p :: !result; done; !result with End_of_file -> close_in ic; !result ;;   let loaded = (loadPoints "Points.txt") in let start = Sys.time() in let c = closestPair loaded in let taken = Sys.time() -. start in Printf.printf "Took %f [s]\n" taken;   match c with | None -> Printf.printf "No closest pair\n" | Some(seg) -> let a = fst seg in let b = snd seg in   Printf.printf "(%f, %f) (%f, %f) Dist %f\n" a.x a.y b.x b.y (dist c)    
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
#TXR
TXR
(let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10)))) [mapcar call [funs 0..-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
#Wren
Wren
var fs = List.filled(10, null) for (i in 0...fs.count) { fs[i] = Fn.new { i * i } }   for (i in 0...fs.count-1) System.print("Function #%(i):  %(fs[i].call())")
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
#JavaScript
JavaScript
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2; const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1)); const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]]; const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2);   const findC = (...args) => { const [p1, p2, s] = args; const solve = solveF(p1, s); const halfDist = hDist(p1, p2);   let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `; switch (Math.sign(s - halfDist)) { case 0: msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` : 'Radius Zero'; break; case 1: if (!halfDist) { msg += 'Coincident point. Infinite solutions'; } else { let theta = pAng(p1, p2); let theta2 = Math.acos(halfDist / s); [1, -1].map(e => solve(theta + e * theta2)).forEach( e => msg += `Circle at ${e} `); } break; case -1: msg += 'No intersection. Points further apart than circle diameter'; break; } return msg; };     [ [[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] ].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`));  
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).
#Java
Java
public 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"; } }   public static void main(String[] args) { int years[]={1935,1938,1968,1972,1976,1984,1985,2017}; for(int i=0;i<years.length;i++) { System.out.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
#Crystal
Crystal
def check_file(filename : String) if File.directory?(filename) puts "#{filename} is a directory" elsif File.exists?(filename) puts "#{filename} is a file" else puts "#{filename} does not exist" end end   check_file("input.txt") check_file("docs") check_file("/input.txt") check_file("/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
#D
D
import std.stdio, std.file, std.path;   void verify(in string name) { if (name.exists()) writeln("'", name, "' exists"); else writeln("'", name, "' doesn't exist"); }   void main() { // check in current working dir verify("input.txt"); verify("docs");   // check in root verify(dirSeparator ~ "input.txt"); verify(dirSeparator ~ "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
#FreeBASIC
FreeBASIC
  ' Chaos game Const ancho = 320, alto = 240 Dim As Integer x, y, iteracion, vertice x = Int(Rnd * ancho) y = Int(Rnd * alto)   Screenres ancho, alto, 8 Cls   For iteracion = 1 To 30000 vertice = Int(Rnd * 3) + 1 Select Case vertice Case 1 x = x / 2 y = y / 2 vertice = 4 'red Case 2 x = (ancho/2) + ((ancho/2)-x) / 2 y = alto - (alto-y) / 2 vertice = 2 'green Case 3 x = ancho - (ancho-x) / 2 y = y / 2 vertice = 1 'blue End Select Pset (x,y),vertice Next iteracion Sleep 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.
#Java
Java
import java.io.*; import java.net.*; import java.util.*;   public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>();   public ChatServer(int port) { this.port = port; }   public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } }   private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; }   private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); }   private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).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 = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } }   public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null;   public Client(Socket socket) { this.socket = socket; }   public 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 = null; while ((line = input.readLine()) != null) { if (clientName == null) { 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 e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } }   public void write(String msg) throws IOException { output.write(msg); output.flush(); }   public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } }   public 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.
#Perl
Perl
use Math::BigRat try=>"GMP";   sub taneval { my($coef,$f) = @_; $f = Math::BigRat->new($f) unless ref($f); return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0; my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) ); ($a+$b)/(1-$a*$b); }   sub tans { my @xs=@_; return taneval(@{$xs[0]}) if scalar(@xs)==1; my($a,$b) = ( tans(@xs[0..($#xs>>1)]), tans(@xs[($#xs>>1)+1..$#xs]) ); ($a+$b)/(1-$a*$b); }   sub test { printf "%5s (%s)\n", (tans(@_)==1)?"OK":"Error", join(" ",map{"[@$_]"} @_); }   test([1,'1/2'], [1,'1/3']); test([2,'1/3'], [1,'1/7']); test([4,'1/5'], [-1,'1/239']); test([5,'1/7'],[2,'3/79']); test([5,'29/278'],[7,'3/79']); test([1,'1/2'],[1,'1/5'],[1,'1/8']); test([4,'1/5'],[-1,'1/70'],[1,'1/99']); test([5,'1/7'],[4,'1/53'],[2,'1/4443']); test([6,'1/8'],[2,'1/57'],[1,'1/239']); test([8,'1/10'],[-1,'1/239'],[-4,'1/515']); test([12,'1/18'],[8,'1/57'],[-5,'1/239']); test([16,'1/21'],[3,'1/239'],[4,'3/1042']); test([22,'1/28'],[2,'1/443'],[-5,'1/1393'],[-10,'1/11018']); test([22,'1/38'],[17,'7/601'],[10,'7/8149']); test([44,'1/57'],[7,'1/239'],[-12,'1/682'],[24,'1/12943']); test([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12943']); test([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.
#BQN
BQN
FromCharCode ← @⊸+ @⊸+ FromCharCode 97 'a' FromCharCode 97‿67‿126 "aC~" FromCharCode⁼ 'a' 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.
#Bracmat
Bracmat
( put $ ( str $ ( "\nLatin a ISO-9959-1: " asc$a " = " chr$97 " UTF-8: " utf$a " = " chu$97 \n "Cyrillic а (UTF-8): " utf$а " = " chu$1072 \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.
#Kotlin
Kotlin
// version 1.0.6   fun cholesky(a: DoubleArray): DoubleArray { val n = Math.sqrt(a.size.toDouble()).toInt() val l = DoubleArray(a.size) var s: Double for (i in 0 until n) for (j in 0 .. i) { s = 0.0 for (k in 0 until j) s += l[i * n + k] * l[j * n + k] l[i * n + j] = when { (i == j) -> Math.sqrt(a[i * n + i] - s) else -> 1.0 / l[j * n + j] * (a[i * n + j] - s) } } return l }   fun showMatrix(a: DoubleArray) { val n = Math.sqrt(a.size.toDouble()).toInt() for (i in 0 until n) { for (j in 0 until n) print("%8.5f ".format(a[i * n + j])) println() } }   fun main(args: Array<String>) { val m1 = doubleArrayOf(25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0) val c1 = cholesky(m1) showMatrix(c1) println() val m2 = doubleArrayOf(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) val c2 = cholesky(m2) showMatrix(c2) }
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
#Lua
Lua
-- Cheryl's Birthday in Lua 6/15/2020 db   local function Date(mon,day) return { mon=mon, day=day, valid=true } end   local choices = { Date("May", 15), Date("May", 16), Date("May", 19), Date("June", 17), Date("June", 18), Date("July", 14), Date("July", 16), Date("August", 14), Date("August", 15), Date("August", 17) }   local function apply(t, f) for k, v in ipairs(t) do f(k, v) end end   local function filter(t, f) local result = {} for k, v in ipairs(t) do if f(k, v) then result[#result+1] = v end end return result end   local function map(t, f) local result = {} for k, v in ipairs(t) do result[#result+1] = f(k, v) end return result end   local function count(t) return #t end local function isvalid(k, v) return v.valid end local function invalidate(k, v) v.valid = false end local function remaining() return filter(choices, isvalid) end   local function listValidChoices() print(" " .. table.concat(map(remaining(), function(k, v) return v.mon .. " " .. v.day end), ", ")) print() end   print("Cheryl offers these ten choices:") listValidChoices()   print("1) Albert knows that Bernard also cannot yet know, so cannot be a month with a unique day, leaving:") apply(remaining(), function(k, v) if count(filter(choices, function(k2, v2) return v.day==v2.day end)) == 1 then apply(filter(remaining(), function(k2, v2) return v.mon==v2.mon end), invalidate) end end) listValidChoices()   print("2) After Albert's revelation, Bernard now knows, so day must be unique, leaving:") apply(remaining(), function(k, v) local subset = filter(remaining(), function(k2, v2) return v.day==v2.day end) if count(subset) > 1 then apply(subset, invalidate) end end) listValidChoices()   print("3) After Bernard's revelation, Albert now knows, so month must be unique, leaving only:") apply(remaining(), function(k, v) local subset = filter(remaining(), function(k2, v2) return v.mon==v2.mon end) if count(subset) > 1 then apply(subset, invalidate) end end) listValidChoices()
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.
#Tcl
Tcl
package require Tcl 8.5 package require Thread   namespace eval checkpoint { namespace export {[a-z]*} namespace ensemble create variable members {} variable waiting {} variable event # Back-end of join operation proc Join {id} { variable members variable counter if {$id ni $members} { lappend members $id } return $id } # Back-end of leave operation proc Leave {id} { variable members set idx [lsearch -exact $members $id] if {$idx > -1} { set members [lreplace $members $idx $idx] variable event if {![info exists event]} { set event [after idle ::checkpoint::Release] } } return } # Back-end of deliver operation proc Deliver {id} { variable waiting lappend waiting $id   variable event if {![info exists event]} { set event [after idle ::checkpoint::Release] } return } # Releasing is done as an "idle" action to prevent deadlocks proc Release {} { variable members variable waiting variable event unset event if {[llength $members] != [llength $waiting]} return set w $waiting set waiting {} foreach id $w { thread::send -async $id {incr ::checkpoint::Delivered} } }   # Make a thread and attach it to the public API of the checkpoint proc makeThread {{script ""}} { set id [thread::create thread::wait] thread::send $id { namespace eval checkpoint { namespace export {[a-z]*} namespace ensemble create   # Call to actually join the checkpoint group proc join {} { variable checkpoint thread::send $checkpoint [list \  ::checkpoint::Join [thread::id]] } # Call to actually leave the checkpoint group proc leave {} { variable checkpoint thread::send $checkpoint [list \  ::checkpoint::Leave [thread::id]] } # Call to wait for checkpoint synchronization proc deliver {} { variable checkpoint # Do this from within the [vwait] to ensure that we're already waiting after 0 [list thread::send $checkpoint [list \  ::checkpoint::Deliver [thread::id]]] vwait ::checkpoint::Delivered } } } thread::send $id [list set ::checkpoint::checkpoint [thread::id]] thread::send $id $script return $id }   # Utility to help determine whether the checkpoint is in use proc anyJoined {} { variable members expr {[llength $members] > 0} } }
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Lisaac
Lisaac
+ vector : ARRAY[INTEGER]; vector := ARRAY[INTEGER].create_with_capacity 32 lower 0; vector.add_last 1; vector.add_last 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
#Perl5i
Perl5i
  use perl5i::2;   # ---------------------------------------- # generate combinations of length $n consisting of characters # from the sorted set @set, using each character once in a # combination, with sorted strings in sorted order. # # Returns a list of array references, each containing one combination. # func combine($n, @set) { return unless @set; return map { [ $_ ] } @set if $n == 1;   my ($head) = shift @set; my @result = combine( $n-1, @set ); for my $subarray ( @result ) { $subarray->unshift( $head ); } return ( @result, combine( $n, @set ) ); }   say @$_ for combine( 3, ('a'..'e') );  
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.
#Scheme
Scheme
(if <test> <consequent> <alternate>)
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}}} .
#Icon_and_Unicon
Icon and Unicon
link numbers # for gcd()   procedure main() write(cr([3,5,7],[2,3,2]) | "No solution!") write(cr([10,4,9],[11,22,19]) | "No solution!") end   procedure cr(n,a) if 1 ~= gcd(n[i := !*n],a[i]) then fail # Not pairwise coprime (prod := 1, sm := 0) every prod *:= !n every p := prod/(ni := n[i := !*n]) do sm +:= a[i] * mul_inv(p,ni) * p return sm%prod end   procedure mul_inv(a,b) if b = 1 then return 1 (b0 := b, x0 := 0, x1 := 1) while q := (1 < a)/b do { (t := a, a := b, b := t%b) (t := x0, x0 := x1-q*t, x1 := t) } return if x1 < 0 then x1+b0 else x1 end
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Python
Python
# https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors from sympy import divisors   def chowla(n): return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n   def is_prime(n): return chowla(n) == 0   def primes_to(n): return sum(chowla(i) == 0 for i in range(2, n))   def perfect_between(n, m): c = 0 print(f"\nPerfect numbers between [{n:_}, {m:_})") for i in range(n, m): if i > 1 and chowla(i) == i - 1: print(f" {i:_}") c += 1 print(f"Found {c} Perfect numbers between [{n:_}, {m:_})")     if __name__ == '__main__': for i in range(1, 38): print(f"chowla({i:2}) == {chowla(i)}") for i in range(2, 6): print(f"primes_to({10**i:_}) == {primes_to(10**i):_}") perfect_between(1, 1_000_000) print() for i in range(6, 8): print(f"primes_to({10**i:_}) == {primes_to(10**i):_}") perfect_between(1_000_000, 35_000_000)
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.
#Logtalk
Logtalk
:- object(metaclass, instantiates(metaclass)).   :- public(new/2). new(Instance, Value) :- self(Class), create_object(Instance, [instantiates(Class)], [], [state(Value)]).   :- end_object.   :- object(class, instantiates(metaclass)).   :- public(method/1). method(Value) :- ::state(Value).   :- private(state/1).   :- end_object.
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.
#Lua
Lua
myclass = setmetatable({ __index = function(z,i) return myclass[i] end, --this makes class variables a possibility setvar = function(z, n) z.var = n end }, { __call = function(z,n) return setmetatable({var = n}, myclass) end })   instance = myclass(3)   print(instance.var) -->3   instance:setvar(6)   print(instance.var) -->6
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)
#Oz
Oz
declare fun {Distance X1#Y1 X2#Y2} {Sqrt {Pow X2-X1 2.0} + {Pow Y2-Y1 2.0}} end   %% brute force fun {BFClosestPair Points=P1|P2|_} Ps = {List.toTuple unit Points} %% for efficient random access N = {Width Ps} MinDist = {NewCell {Distance P1 P2}} MinPoints = {NewCell P1#P2} in for I in 1..N-1 do for J in I+1..N do IJDist = {Distance Ps.I Ps.J} in if IJDist < @MinDist then MinDist := IJDist MinPoints := Ps.I#Ps.J end end end @MinPoints end   %% divide and conquer fun {ClosestPair Points} case {ClosestPair2 {Sort Points {LessThanBy X}} {Sort Points {LessThanBy Y}}} of Distance#Pair then Pair end end   %% XP: points sorted by X, YP: sorted by Y %% returns a pair Distance#Pair fun {ClosestPair2 XP YP} N = {Length XP} = {Length YP} in if N =< 3 then P = {BFClosestPair XP} in {Distance P.1 P.2}#P else XL XR {List.takeDrop XP (N div 2) ?XL ?XR} XM = {Nth XP (N div 2)}.X YL YR {List.partition YP fun {$ P} P.X =< XM end ?YL ?YR} DL#PairL = {ClosestPair2 XL YL} DR#PairR = {ClosestPair2 XR YR} DMin#PairMin = if DL < DR then DL#PairL else DR#PairR end YSList = {Filter YP fun {$ P} {Abs XM-P.X} < DMin end} YS = {List.toTuple unit YSList} %% for efficient random access NS = {Width YS} Closest = {NewCell DMin} ClosestPair = {NewCell PairMin} in for I in 1..NS-1 do for K in I+1..NS while:YS.K.Y - YS.I.Y < DMin do DistKI = {Distance YS.K YS.I} in if DistKI < @Closest then Closest := DistKI ClosestPair := YS.K#YS.I end end end @Closest#@ClosestPair end end   %% To access components when points are represented as pairs X = 1 Y = 2   %% returns a less-than predicate that accesses feature F fun {LessThanBy F} fun {$ A B} A.F < B.F end end   fun {Random Min Max} Min + {Int.toFloat {OS.rand}} * (Max-Min) / {Int.toFloat {OS.randLimits _}} end   fun {RandomPoint} {Random 0.0 100.0}#{Random 0.0 100.0} end   Points = {MakeList 5} in {ForAll Points RandomPoint} {Show Points} {Show {ClosestPair Points}}
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
#Yabasic
Yabasic
  dim funcs$(10)   sub power2(i) return i * i end sub   for i = 1 to 10 funcs$(i) = "power2" next   for i = 1 to 10 print execute(funcs$(i), i) next  
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
#zkl
zkl
(0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64 list:=(0).pump(10,List,fcn(i){i*i}.fp); foreach n in (list.len()-1) { list[n]().println() } list.run(True).println()
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
#jq
jq
# circle_centers is defined here as a filter. # Input should be an array [x1, y1, x2, y2, r] giving the co-ordinates # of the two points and a radius. # If there is one solution, the output is the circle center; # if there are two solutions centered at [x1, y1] and [x2, y2], # then the output is [x1, y1, x2, y2]; # otherwise an explanatory string is returned.   def circle_centers: def sq: .*.; def c(x3; y1; y2; r; d): x3 + ((r|sq - ((d/2)|sq)) | sqrt) * (y1-y2)/d;   .[0] as $x1 | .[1] as $y1 | .[2] as $x2 | .[3] as $y2 | .[4] as $r | ((($x2-$x1)|sq) + (($y2-$y1)|sq) | sqrt) as $d | (($x1+$x2)/2) as $x3 | (($y1+$y2)/2) as $y3 | c($x3; $y1; $y2; $r; $d) as $cx1 | c($y3; $x2; $x2; $r; $d) as $cy1 | (- c(-$x3; $y1; $y2; $r; $d)) as $cx2 | (- c(-$y3; $x2; $x2; $r; $d)) as $cy2 | if $d == 0 and $r == 0 then [$x1, $y1] # special case elif $d == 0 then "infinitely many circles can be drawn" elif $d > $r*2 then "points are too far from each other" elif 0 > $r then "radius is not valid" elif ($cx1 and $cy1 and $cx2 and $cy2) | not then "no solution" else [$cx1, $cy1, $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).
#JavaScript
JavaScript
(() => { "use strict";   // ---------- TRADITIONAL CALENDAR STRINGS -----------   // ats :: Array Int (String, String) const ats = () => // 天干 tiangan – 10 heavenly stems zip( chars("甲乙丙丁戊己庚辛壬癸") )( words("jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi") );     // ads :: Array Int (String, String) const ads = () => // 地支 dizhi – 12 terrestrial branches zip( 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) const aws = () => // 五行 wuxing – 5 elements zip3( chars("木火土金水") )( words("mù huǒ tǔ jīn shuǐ") )( words("wood fire earth metal water") );     // axs :: Array Int (String, String, String) const axs = () => // 十二生肖 shengxiao – 12 symbolic animals zip3( 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) const ays = () => // 阴阳 yinyang zip( chars("阳阴") )( words("yáng yīn") );     // --------------- TRADITIONAL CYCLES ---------------- const zodiac = y => { const iYear = y - 4, iStem = iYear % 10, iBranch = iYear % 12, [hStem, pStem] = ats()[iStem], [hBranch, pBranch] = ads()[iBranch], [hElem, pElem, eElem] = aws()[quot(iStem)(2)], [hAnimal, pAnimal, eAnimal] = axs()[iBranch], [hYinyang, pYinyang] = ays()[iYear % 2];   return [ [ show(y), hStem + hBranch, hElem, hAnimal, hYinyang ], ["", pStem + pBranch, pElem, pAnimal, pYinyang], [ "", `${show((iYear % 60) + 1)}/60`, eElem, eAnimal, "" ] ]; };     // ---------------------- TEST ----------------------- const main = () => [ 1935, 1938, 1968, 1972, 1976, 1984, new Date().getFullYear() ] .map(showYear) .join("\n\n");     // ------------------- FORMATTING -------------------- // fieldWidths :: [[Int]] const fieldWidths = [ [6, 10, 7, 8, 3], [6, 11, 8, 8, 4], [6, 11, 8, 8, 4] ];     // showYear :: Int -> String const showYear = y => zipWith(zip)(fieldWidths)(zodiac(y)) .map( row => row.map( ([n, s]) => s.padEnd(n, " ") ) .join("") ) .join("\n");     // ---------------- GENERIC FUNCTIONS ----------------   // chars :: String -> [Char] const chars = s => [...s];     // quot :: Integral a => a -> a -> a const quot = n => m => Math.trunc(n / m);     // show :: Int -> a -> Indented String // show :: a -> String const show = (...x) => JSON.stringify.apply( null, x.length > 1 ? [ x[1], null, x[0] ] : x );     // words :: String -> [String] const words = s => // List of space-delimited sub-strings. s.split(/\s+/u);     // zip :: [a] -> [b] -> [(a, b)] const zip = xs => // The paired members of xs and ys, up to // the length of the shorter of the two lists. ys => Array.from({ length: Math.min(xs.length, ys.length) }, (_, i) => [xs[i], ys[i]]);     // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] const zip3 = xs => ys => zs => xs.slice( 0, Math.min(...[xs, ys, zs].map(x => x.length)) ) .map((x, i) => [x, ys[i], zs[i]]);     // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => xs.map( (x, i) => f(x)(ys[i]) ).slice( 0, Math.min(xs.length, ys.length) );     // MAIN --- return main(); })();
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
#DBL
DBL
; ; Check file and directory exists for DBL version 4 by Dario B. ; PROC ;------------------------------------------------------------------ XCALL FLAGS (0007000000,1)  ;Suppress STOP message   CLOSE 1 OPEN (1,O,'TT:')    ;The file path can be written as:  ; "input.txt" (current directory)  ; "/directory/input.txt" (complete path)  ; "DEV:input.txt" (device DEV defined in shell)  ; "$DEV/input.txt" (device DEV defined in shell) CLOSE 2 OPEN (2,I,"input.txt") [ERR=NOFIL] CLOSE 2    ;Check directory (unix/linux systems) CLOSE 2 OPEN (2,O,"/docs/.") [ERR=NODIR]   GOTO CLOS   ;-------------------------------------------------------- NOFIL, DISPLAY (1,"File input.txt not found!",10) GOTO CLOS   NODIR, DISPLAY (1,"Directory /docs not found!",10) GOTO CLOS   CLOS, CLOSE 1 CLOSE 2 STOP
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
#DCL
DCL
$ if f$search( "input.txt" ) .eqs. "" $ then $ write sys$output "input.txt not found" $ else $ write sys$output "input.txt found" $ endif $ if f$search( "docs.dir" ) .eqs. "" $ then $ write sys$output "directory docs not found" $ else $ write sys$output "directory docs found" $ endif $ if f$search( "[000000]input.txt" ) .eqs. "" $ then $ write sys$output "[000000]input.txt not found" $ else $ write sys$output "[000000]input.txt found" $ endif $ if f$search( "[000000]docs.dir" ) .eqs. "" $ then $ write sys$output "directory [000000]docs not found" $ else $ write sys$output "directory [000000]docs found" $ endif
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
#F.C5.8Drmul.C3.A6
Fōrmulæ
offset = 32; //Distance from triangle vertices to edges of window   //triangle vertex coordinates x1 = room_width / 2; y1 = offset; x2 = room_width - offset; y2 = room_height - offset; x3 = offset; y3 = room_height - offset;   //Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step event) vx = 0; vy = 0;   //Coords of current point px = random(room_width); py = random(room_height);   //Make sure the point is within the triangle while(!point_in_triangle(px, py, x1, y1, x2, y2, x3, y3)) { px = random(room_width); py = random(room_height); }   vertex = 0; //This determines which vertex coords are chosen max_iterations = 8000; step = true; //Used with the interval alarm to change the step speed step_count = 0; interval = 1; //Number of frames between each step. 1 = no delay alarm[0] = interval;
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.
#JavaScript
JavaScript
const net = require("net"); const EventEmitter = require("events").EventEmitter;   /******************************************************************************* * ChatServer * * Manages connections, users, and chat messages. ******************************************************************************/   class ChatServer { constructor() { this.chatters = {}; this.server = net.createServer(this.handleConnection.bind(this)); this.server.listen(1212, "localhost"); } isNicknameLegal(nickname) { // A nickname may contain letters or numbers only, // and may only be used once. if (nickname.replace(/[A-Za-z0-9]*/, '') !== "") { return false; } for (const used_nick in this.chatters) { if (used_nick === nickname) { return false; } } return true; } handleConnection(connection) { console.log(`Incoming connection from ${connection.remoteAddress}`); connection.setEncoding("utf8");   let chatter = new Chatter(connection, this); chatter.on("chat", this.handleChat.bind(this)); chatter.on("join", this.handleJoin.bind(this)); chatter.on("leave", this.handleLeave.bind(this)); } handleChat(chatter, message) { this.sendToEveryChatterExcept(chatter, chatter.nickname + ": " + message); } handleJoin(chatter) { console.log(`${chatter.nickname} has joined the chat.`); this.sendToEveryChatter(`${chatter.nickname} has joined the chat.`); this.addChatter(chatter); } handleLeave(chatter) { console.log(`${chatter.nickname} has left the chat.`); this.removeChatter(chatter); this.sendToEveryChatter(`${chatter.nickname} has left the chat.`); } addChatter(chatter) { this.chatters[chatter.nickname] = chatter; } removeChatter(chatter) { delete this.chatters[chatter.nickname]; } sendToEveryChatter(data) { for (const nickname in this.chatters) { this.chatters[nickname].send(data); } } sendToEveryChatterExcept(chatter, data) { for (const nickname in this.chatters) { if (nickname !== chatter.nickname) { this.chatters[nickname].send(data); } } } }     /******************************************************************************* * Chatter * * Represents a single user/connection in the chat server. ******************************************************************************/   class Chatter extends EventEmitter { constructor(socket, server) { super();   this.socket = socket; this.server = server; this.nickname = ""; this.lineBuffer = new SocketLineBuffer(socket);   this.lineBuffer.on("line", this.handleNickname.bind(this)); this.socket.on("close", this.handleDisconnect.bind(this));   this.send("Welcome! What is your nickname?"); } handleNickname(nickname) { if (server.isNicknameLegal(nickname)) { this.nickname = nickname; this.lineBuffer.removeAllListeners("line"); this.lineBuffer.on("line", this.handleChat.bind(this)); this.send(`Welcome to the chat, ${nickname}!`); this.emit("join", this); } else { this.send("Sorry, but that nickname is not legal or is already in use!"); this.send("What is your nickname?"); } } handleChat(line) { this.emit("chat", this, line); } handleDisconnect() { this.emit("leave", this); } send(data) { this.socket.write(data + "\r\n"); } };     /******************************************************************************* * SocketLineBuffer * * Listens for and buffers incoming data on a socket and emits a 'line' event * whenever a complete line is detected. ******************************************************************************/   class SocketLineBuffer extends EventEmitter { constructor(socket) { super();   this.socket = socket; this.buffer = "";   this.socket.on("data", this.handleData.bind(this)); } handleData(data) { for (let i = 0; i < data.length; i++) { const char = data.charAt(i); this.buffer += char; if (char == "\n") { this.buffer = this.buffer.replace("\r\n", ""); this.buffer = this.buffer.replace("\n", ""); this.emit("line", this.buffer); this.buffer = ""; } } } };     // Start the server! server = new ChatServer();
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Phix
Phix
with javascript_semantics procedure test(atom a) if -3*PI/4 >= a then ?9/0 end if if 5*PI/4 <= a then ?9/0 end if string s = sprint(tan(a)) ?s -- or test for "1.0"/"1", but not 1.0 end procedure test( arctan(1 / 2) + arctan(1 / 3)) test( 2*arctan(1 / 3) + arctan(1 / 7)) test( 4*arctan(1 / 5) - arctan(1 / 239)) test( 5*arctan(1 / 7) + 2*arctan(3 / 79)) test( 5*arctan(29/ 278) + 7*arctan(3 / 79)) test( arctan(1 / 2) + arctan(1 / 5) + arctan(1 / 8)) test( 4*arctan(1 / 5) - arctan(1 / 70) + arctan(1 / 99)) test( 5*arctan(1 / 7) + 4*arctan(1 / 53) + 2*arctan(1 / 4443)) test( 6*arctan(1 / 8) + 2*arctan(1 / 57) + arctan(1 / 239)) test( 8*arctan(1 / 10) - arctan(1 / 239) - 4*arctan(1 / 515)) test(12*arctan(1 / 18) + 8*arctan(1 / 57) - 5*arctan(1 / 239)) test(16*arctan(1 / 21) + 3*arctan(1 / 239) + 4*arctan(3 / 1042)) test(22*arctan(1 / 28) + 2*arctan(1 / 443) - 5*arctan(1 / 1393) - 10*arctan(1 / 11018)) test(22*arctan(1 / 38) + 17*arctan(7 / 601) +10*arctan(7 / 8149)) test(44*arctan(1 / 57) + 7*arctan(1 / 239) -12*arctan(1 / 682) + 24*arctan(1 / 12943)) test(88*arctan(1 / 172) + 51*arctan(1 / 239) +32*arctan(1 / 682) + 44*arctan(1 / 5357) + 68*arctan(1 / 12943)) ?"===" test(88*arctan(1 / 172) + 51*arctan(1 / 239) + 32*arctan(1 / 682) + 44*arctan(1 / 5357) + 68*arctan(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.
#C
C
#include <stdio.h>   int main() { printf("%d\n", 'a'); /* prints "97" */ printf("%c\n", 97); /* prints "a"; we don't have to cast because printf is type agnostic */ return 0; }
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.
#C.23
C#
using System;   namespace RosettaCode.CharacterCode { class Program { static void Main(string[] args) { Console.WriteLine((int) 'a'); //Prints "97" Console.WriteLine((char) 97); //Prints "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.
#Lobster
Lobster
import std   // choleskyLower returns the cholesky decomposition of a symmetric real // matrix. The matrix must be positive definite but this is not checked def choleskyLower(order, a) -> [float]: let l = map(a.length): 0.0 var row, col = 1, 1 var dr = 0 // index of diagonal element at end of row var dc = 0 // index of diagonal element at top of column for(a) e, i: if i < dr: let d = (e - l[i]) / l[dc] l[i] = d var ci, cx = col, dc var j = i + 1 while j <= dr: cx += ci ci += 1 l[j] += d * l[cx] j += 1 col += 1 dc += col else: l[i] = sqrt(e - l[i]) row += 1 dr += row col = 1 dc = 0 return l   // symmetric.print prints a square matrix from the packed representation, // printing the upper triange as a transpose of the lower def print_symmetric(order, s): //const eleFmt = "%10.5f " var str = "" var row, diag = 1, 0 for(s) e, i: str += e + " " // format? if i == diag: var j, col = diag+row, row while col < order: str += s[j] + " " // format? col++ j += col print(str); str = "" row += 1 diag += row   // lower.print prints a square matrix from the packed representation, // printing the upper triangle as all zeros. def print_lower(order, l): //const eleFmt = "%10.5f " var str = "" var row, diag = 1, 0 for(l) e, i: str += e + " " // format? if i == diag: var j = row while j < order: str += 0.0 + " " // format? j += 1 print(str); str = "" row += 1 diag += row   def demo(order, a): print("A:") print_symmetric(order, a) print("L:") print_lower(order, choleskyLower(order, a))   demo(3, [25.0, 15.0, 18.0, -5.0, 0.0, 11.0])   demo(4, [18.0, 22.0, 70.0, 54.0, 86.0, 174.0, 42.0, 62.0, 134.0, 106.0])  
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.
#Maple
Maple
> A := << 25, 15, -5; 15, 18, 0; -5, 0, 11 >>; [25 15 -5] [ ] A := [15 18 0] [ ] [-5 0 11]   > B := << 18, 22, 54, 42; 22, 70, 86, 62; 54, 86, 174, 134; 42, 62, 134, 106>>; [18 22 54 42] [ ] [22 70 86 62] B := [ ] [54 86 174 134] [ ] [42 62 134 106]   > use LinearAlgebra in > LUDecomposition( A, method = Cholesky ); > LUDecomposition( B, method = Cholesky ); > evalf( % ); > end use; [ 5 0 0] [ ] [ 3 3 0] [ ] [-1 1 3]   [ 1/2 ] [3 2 0 0 0 ] [ ] [ 1/2 1/2 ] [11 2 2 97 ] [------- ------- 0 0 ] [ 3 3 ] [ ] [ 1/2 1/2 ] [ 1/2 30 97 2 6402 ] [9 2 -------- --------- 0 ] [ 97 97 ] [ ] [ 1/2 1/2 1/2] [ 1/2 16 97 74 6402 8 33 ] [7 2 -------- ---------- -------] [ 97 3201 33 ]   [4.242640686 0. 0. 0. ] [ ] [5.185449728 6.565905202 0. 0. ] [ ] [12.72792206 3.046038495 1.649742248 0. ] [ ] [9.899494934 1.624553864 1.849711006 1.392621248]
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
opts = Tuples[{{"May"}, {15, 16, 19}}]~Join~Tuples[{{"June"}, {17, 18}}]~Join~Tuples[{{"July"}, {14, 16}}]~Join~Tuples[{{"August"}, {14, 15, 17}}]; monthsdelete = Select[GatherBy[opts, Last], Length /* EqualTo[1]][[All, 1, 1]]; opts = DeleteCases[opts, {Alternatives @@ monthsdelete, _}] removedates = Catenate@Select[GatherBy[opts, Last], Length /* GreaterThan[1]]; opts = DeleteCases[opts, Alternatives @@ removedates] Select[GatherBy[opts, First], Length /* EqualTo[1]]
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
#Nim
Nim
import tables import sets import strformat   type Date = tuple[month: string, day: int]   const Dates = [Date ("May", 15), ("May", 16), ("May", 19), ("June", 17), ("June", 18), ("July", 14), ("July", 16), ("August", 14), ("August", 15), ("August", 17)]   const   MonthTable: Table[int, HashSet[string]] = static: var t: Table[int, HashSet[string]] for date in Dates: t.mgetOrPut(date.day, initHashSet[string]()).incl(date.month) t   DayTable: Table[string, HashSet[int]] = static: var t: Table[string, HashSet[int]] for date in Dates: t.mgetOrPut(date.month, initHashSet[int]()).incl(date.day) t   var possibleMonths: HashSet[string] # Set of possible months. var possibleDays: HashSet[int] # Set of possible days.     # Albert: I don't know when Cheryl's birthday is, ... # => eliminate months with a single possible day. for month, days in DayTable.pairs: if days.len > 1: possibleMonths.incl(month)   # ... but I know that Bernard does not know too. # => eliminate months with one day present only in this month. for month, days in DayTable.pairs: for day in days: if MonthTable[day].len == 1: possibleMonths.excl(month) echo fmt"After first Albert's sentence, possible months are {possibleMonths}."   # Bernard: At first I don't know when Cheryl's birthday is, ... # => eliminate days with a single possible month. for day, months in MonthTable.pairs: if months.len > 1: possibleDays.incl(day)   # ... but I know now. # => eliminate days which are compatible with several months in "possibleMonths". var impossibleDays: HashSet[int] # Days which are eliminated by this sentence. for day in possibleDays: if (MonthTable[day] * possibleMonths).len > 1: impossibleDays.incl(day) possibleDays.excl(impossibleDays) echo fmt"After Bernard's sentence, possible days are {possibleDays}."   # Albert: Then I also know when Cheryl's birthday is. # => eliminate months which are compatible with several days in "possibleDays". var impossibleMonths: HashSet[string] # Months which are eliminated by this sentence. for month in possibleMonths: if (DayTable[month] * possibleDays).len > 1: impossibleMonths.incl(month) possibleMonths.excl(impossibleMonths)   doAssert possibleMonths.len == 1 let month = possibleMonths.pop() echo fmt"After second Albert's sentence, remaining month is {month}..."   possibleDays = possibleDays * DayTable[month] doAssert possibleDays.len == 1 let day = possibleDays.pop() echo fmt"and thus remaining day is {day}."   echo "" echo fmt"So birthday date is {month} {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.
#Wren
Wren
import "random" for Random import "scheduler" for Scheduler import "timer" for Timer import "/ioutil" for Input   var rgen = Random.new() var nWorkers = 0 var nTasks = 0 var nFinished = 0   var worker = Fn.new { |id| var workTime = rgen.int(100, 1000) // 100..999 msec. System.print("Worker %(id) will work for %(workTime) msec.") Timer.sleep(workTime) nFinished = nFinished + 1 System.print("Worker %(id) is ready.") }   var checkPoint = Fn.new { while (nFinished != nWorkers) { Timer.sleep(10) } nFinished = 0 // reset }   var runTasks = Fn.new { for (i in 1..nTasks) { System.print("\nStarting task number %(i).") var first = rgen.int(1, nWorkers + 1) // randomize first worker to start // schedule other workers to start while another fiber is sleeping for (j in 1..nWorkers) { if (j != first) Scheduler.add { worker.call(j) } } worker.call(first) // start first worker checkPoint.call() // start checkPoint } }   nWorkers = Input.integer("Enter number of workers to use: ", 1) nTasks = Input.integer("Enter number of tasks to complete: ", 1) runTasks.call()
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
#Logo
Logo
collection = {0, '1'} print(collection[1]) -- prints 0   collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs print(collection["foo"]) -- prints 0 print(collection.foo) -- syntactic sugar, also prints 0   collection = {0, '1', ["foo"] = 0, ["bar"] = '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
#Phix
Phix
with javascript_semantics procedure comb(integer pool, needed, done=0, sequence chosen={}) if needed=0 then -- got a full set ?chosen -- (or use a routine_id, result arg, or whatever) return end if if done+needed>pool then return end if -- cannot fulfil -- get all combinations with and without the next item: done += 1 comb(pool,needed-1,done,append(deep_copy(chosen),done)) comb(pool,needed,done,chosen) end procedure comb(5,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.
#Scilab
Scilab
if condition1 then instructions1 [elseif condition2 then instructions2] .... [else instructionse] end
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}}} .
#J
J
crt =: (1 + ] - {:@:[ -: {.@:[ | ])^:_&0@:,:
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}}} .
#Java
Java
import static java.util.Arrays.stream;   public class ChineseRemainderTheorem {   public static int chineseRemainder(int[] n, int[] a) {   int prod = stream(n).reduce(1, (i, j) -> i * j);   int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; }   private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1;   if (b == 1) return 1;   while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; }   if (x1 < 0) x1 += b0;   return x1; }   public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(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.
#Racket
Racket
#lang racket   (require racket/fixnum)   (define cache-size 35000000)   (define chowla-cache (make-fxvector cache-size -1))   (define (chowla/uncached n) (for/sum ((i (sequence-filter (λ (x) (zero? (modulo n x))) (in-range 2 (add1 (quotient n 2)))))) i))   (define (chowla n) (if (> n cache-size) (chowla/uncached n) (let ((idx (sub1 n))) (if (negative? (fxvector-ref chowla-cache idx)) (let ((c (chowla/uncached n))) (fxvector-set! chowla-cache idx c) c) (fxvector-ref chowla-cache idx)))))   (define (prime?/chowla n) (and (> n 1) (zero? (chowla n))))   (define (perfect?/chowla n) (and (> n 1) (= n (add1 (chowla n)))))   (define (make-chowla-sieve n) (let ((v (make-vector n 0))) (for* ((i (in-range 2 n)) (j (in-range (* 2 i) n i))) (vector-set! v j (+ i (vector-ref v j)))) (for ((i (in-range 1 n))) (fxvector-set! chowla-cache (sub1 i) (vector-ref v i)))))   (module+ main (define (count-and-report-primes limit) (printf "Primes < ~a: ~a~%" limit (for/sum ((i (sequence-filter prime?/chowla (in-range 2 (add1 limit))))) 1)))   (for ((i (in-range 1 (add1 37)))) (printf "(chowla ~a) = ~a~%" i (chowla i)))   (make-chowla-sieve cache-size)   (for-each count-and-report-primes '(1000 10000 100000 1000000 10000000))   (let ((ns (for/list ((n (sequence-filter perfect?/chowla (in-range 2 35000000)))) n))) (printf "There are ~a perfect numbers <= 35000000: ~a~%" (length ns) ns)))
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.
#Raku
Raku
sub comma { $^i.flip.comb(3).join(',').flip }   sub schnitzel (\Radda, \radDA = 0) { Radda.is-prime ?? !Radda !! ?radDA ?? Radda !! sum flat (2 .. Radda.sqrt.floor).map: -> \RAdda { my \RADDA = Radda div RAdda; next if RADDA * RAdda !== Radda; RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA } }   my \chowder = cache (1..Inf).hyper(:8degree).grep( !*.&schnitzel: 'panini' );   my \mung-daal = lazy gather for chowder -> \panini { my \gazpacho = 2**panini - 1; take gazpacho * 2**(panini - 1) unless schnitzel gazpacho, panini; }   printf "chowla(%2d) = %2d\n", $_, .&schnitzel for 1..37;   say '';   printf "Count of primes up to %10s: %s\n", comma(10**$_), comma chowder.first( * > 10**$_, :k) for 2..7;   say "\nPerfect numbers less than 35,000,000";   .&comma.say for mung-daal[^5];
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.
#M2000_Interpreter
M2000 Interpreter
  Class zz { module bb { Superclass A { unique: counter } Superclass B1 { unique: counter } Superclass B2 { unique: counter } \\ We can make a group Alfa with a member, another group Beta \\ Group Beta can't see parent group, but can see own member groups \\ Group Alfa can see everything in nested groups, in any level, \\ but can't see inside modules/functions/operator/value/set Group Alfa { Group Beta { } } Alfa=A Alfa.Beta=B1 \\ we make 3 groups for marshaling counters \\ each group get a superclass Marshal1=A Marshal2=B1 Marshal3=B2 \\ Now we want to add functionality7 \\ Inc module to add 1 to counter \\ a Value function to return counter \\ Without Value a group return a copy \\ If a group has a value then we can get copy using Group(nameofgroup) \\ just delete Group Marshal1 and remove Rem when we make Marshal1 using a class function Group Marshal1 { Module Inc { For SuperClass {.counter++} } Value { For SuperClass {=.counter} } } Class AnyMarshal { Module Inc { For SuperClass {.counter++} } Value { For SuperClass {=.counter} } } \\ here we merge groups Rem : Marshal1=AnyMarshal() Marshal2=AnyMarshal() Marshal3=AnyMarshal()   \\ So now we see counters (three zero) Print Marshal1, Marshal2, Marshal3 \\ 0, 0, 0 \\ Now we prepare Alfa and Alfa.Beta groups Group Alfa { Group Beta { Function SuperClass.Counter { For SuperClass { =.counter } } } Module PrintData { For SuperClass { Print .counter, This.Beta.SuperClass.Counter() } } } \\ some marshaling to counters Marshal1.inc Marshal2.inc Marshal2.inc Marshal3.inc \\ lets print results Print Marshal1, Marshal2, Marshal3 \\ 1 2 1 \\ Calling Alfa.PrintData Alfa.PrintData \\ 1 2 \\ Merging a group in a group make a change to superclass pointer inside group Alfa.Beta=B2 \\ change supeclass Alfa.PrintData \\ 1 1 For i=1 to 10 : Marshal3.inc : Next i Alfa.PrintData \\ 1 11 Alfa.Beta=B1 \\ change supeclass Alfa.PrintData \\ 1 2 Epsilon=Alfa Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1 -1 Epsilon.PrintData \\ 1 2 Alfa.Beta=B2 \\ change supeclass Alfa.PrintData \\ 1 11 Epsilon.PrintData \\ 1 2 \\ validation being for top group superclass and all members if are same \\ but not for inner superclasses. This maybe change in later revisions of language. Print Valid(@alfa as epsilon), Valid(@alfa.beta as epsilon.beta) \\ -1 0   } } Dim A(10) A(3)=zz() A(3).bb   Report { there is no super like java super in M2000 when we use inheritance through classes see Superclass (example SUP) which is something differnent }     class Shape { private: super.X, super.Y Function super.toString$(a=10) { ="Shape(" + str$(.super.X,"") + ", " + str$(.super.Y,"") + ")" } public: Module final setPosition (px, py) { .super.X <= px .super.Y <= py } Function toString$() { =.super.toString$() } } class MoveShape { Module MoveRelative(xr, yr) { .super.X+=xr .super.Y+=yr } } class Circle as MoveShape as Shape { private: radius public: Module setRadius (r) { .radius <= r } Function toString$() { = .super.toString$() + ": Circle(" + str$(.radius,"") + ")" } }   class Rectangle as MoveShape as Shape { private: height, width public: Module MoveLeftSide (p as *Rectangle) { \\ for same type objects private members are like public for This, p { .super.X<=..super.X+..width .super.Y<=..super.Y } } module setDimensions (h,w) { .height <= h .width <= w } Function toString$() { = .super.toString$() + ": Rectangle(" + str$(.height,"") + " x " + str$(.width,"") + ")" } } c =Circle() r = Rectangle()   r.setPosition 1, 2 r.setDimensions 50, 50 c.setPosition 3, 4 c.setRadius 10 Print r.tostring$() Print c.tostring$() r.MoveRelative 100,100 c.MoveRelative -50,-50 Print r.tostring$() Print c.tostring$()   Report { wokring with pointers like in c++ pointers in M2000 are objects, so null pointer (pc->0&) isn't a zero, but an empty Group (object) } pc->circle() pr->rectangle() pr=>setPosition 1, 2 pr=>setDimensions 50, 50 pc=>setPosition 3, 4 pc=>setRadius 10 Print pr=>tostring$() Print pc=>tostring$() \\ we can open up to ten objects (from one to ten dots, normaly one to three) \\ if we use nestef for object {} also we have up to ten objects in total \\ every for object {} is an area for temporary definitions, after exit from brackets \\ any new definition erased. For pr, pc { .MoveRelative 100,100 ..MoveRelative -50,-50 Print .tostring$() Print ..tostring$() } pr2->rectangle() pr2=>SetDimensions 30, 30 pr2=>MoveLeftSide pr Print pr2=>toString$()    
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.
#MATLAB
MATLAB
function GenericClassInstance = GenericClass(varargin)   if isempty(varargin) %No input arguments GenericClassInstance.classVariable = 0; %Generates a struct else GenericClassInstance.classVariable = varargin{1}; %Generates a struct end   %Converts the struct to a class of type GenericClass GenericClassInstance = class(GenericClassInstance,'GenericClass');   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)
#PARI.2FGP
PARI/GP
closestPair(v)={ my(r=norml2(v[1]-v[2]),at=[1,2]); for(a=1,#v-1, for(b=a+1,#v, if(norml2(v[a]-v[b])<r, at=[a,b]; r=norml2(v[a]-v[b]) ) ) ); [v[at[1]],v[at[2]]] };
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Julia
Julia
  immutable Point{T<:FloatingPoint} x::T y::T end   immutable Circle{T<:FloatingPoint} c::Point{T} r::T end Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T))   using AffineTransforms   function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T) cp = Circle{T}[] r >= 0 || return (cp, "No Solution, Negative Radius") if a == b if abs(r) < 2eps(zero(T)) return (push!(cp, Circle(a)), "Point Solution, Zero Radius") else return (cp, "Infinite Solutions, Indefinite Center") end end ca = Complex(a.x, a.y) cb = Complex(b.x, b.y) d = (ca + cb)/2 tfd = tformtranslate([real(d), imag(d)]) tfr = tformrotate(angle(cb-ca)) tfm = tfd*tfr u = abs(cb-ca)/2 r-u > -5eps(r) || return(cp, "No Solution, Radius Too Small") if r-u < 5eps(r) push!(cp, Circle(apply(Point, tfm*[0.0, 0.0]), r)) return return (cp, "Single Solution, Degenerate Centers") end v = sqrt(r^2 - u^2) for w in [v, -v] push!(cp, Circle(apply(Point, tfm*[0.0, w]), r)) end return (cp, "Two Solutions") 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).
#Julia
Julia
function chinese(year::Int) pinyin = Dict( "甲" => "jiă", "乙" => "yĭ", "丙" => "bĭng", "丁" => "dīng", "戊" => "wù", "己" => "jĭ", "庚" => "gēng", "辛" => "xīn", "壬" => "rén", "癸" => "gŭi", "子" => "zĭ", "丑" => "chŏu", "寅" => "yín", "卯" => "măo", "辰" => "chén", "巳" => "sì", "午" => "wŭ", "未" => "wèi", "申" => "shēn", "酉" => "yŏu", "戌" => "xū", "亥" => "hài", ) elements = ["Wood", "Fire", "Earth", "Metal", "Water"] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] celestial = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"] terrestrial = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"] aspects = ["yang", "yin"] base = 4   cycleyear = year - base   stemnumber = cycleyear % 10 + 1 stemhan = celestial[stemnumber] stempinyin = pinyin[stemhan]   elementnumber = div(stemnumber, 2) + 1 element = elements[elementnumber]   branchnumber = cycleyear % 12 + 1 branchhan = terrestrial[branchnumber] branchpinyin = pinyin[branchhan] animal = animals[branchnumber]   aspectnumber = cycleyear % 2 + 1 aspect = aspects[aspectnumber]   index = cycleyear % 60 + 1   return "$year: $stemhan$branchhan ($stempinyin-$branchpinyin, $element $animal; $aspect - year $index of the cycle)" end   curryr = Dates.year(now()) yrs = [1935, 1938, 1968, 1972, 1976, curryr] foreach(println, map(chinese, yrs))
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
#Delphi
Delphi
program EnsureFileExists;   {$APPTYPE CONSOLE}   uses SysUtils;   begin if FileExists('input.txt') then Writeln('File "input.txt" exists.') else Writeln('File "input.txt" does not exist.');   if FileExists('\input.txt') then Writeln('File "\input.txt" exists.') else Writeln('File "\input.txt" does not exist.');   if DirectoryExists('docs') then Writeln('Directory "docs" exists.') else Writeln('Directory "docs" does not exists.');   if DirectoryExists('\docs') then Writeln('Directory "\docs" exists.') else Writeln('Directory "\docs" does not exists.'); end.
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#GML
GML
offset = 32; //Distance from triangle vertices to edges of window   //triangle vertex coordinates x1 = room_width / 2; y1 = offset; x2 = room_width - offset; y2 = room_height - offset; x3 = offset; y3 = room_height - offset;   //Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step event) vx = 0; vy = 0;   //Coords of current point px = random(room_width); py = random(room_height);   //Make sure the point is within the triangle while(!point_in_triangle(px, py, x1, y1, x2, y2, x3, y3)) { px = random(room_width); py = random(room_height); }   vertex = 0; //This determines which vertex coords are chosen max_iterations = 8000; step = true; //Used with the interval alarm to change the step speed step_count = 0; interval = 1; //Number of frames between each step. 1 = no delay alarm[0] = interval;
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.
#Julia
Julia
  using HttpServer using WebSockets   const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}()   function decodeMessage( msg ) String(copy(msg)) end     wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end   onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end   server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)  
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.
#Python
Python
import re from fractions import Fraction from pprint import pprint as pp     equationtext = '''\ 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) '''   def parse_eqn(equationtext=equationtext): eqn_re = re.compile(r"""(?mx) (?P<lhs> ^ \s* pi/4 \s* = \s*)? # LHS of equation (?: # RHS \s* (?P<sign> [+-])? \s* (?: (?P<mult> \d+) \s* \*)? \s* arctan\( (?P<numer> \d+) / (?P<denom> \d+) )""")   found = eqn_re.findall(equationtext) machins, part = [], [] for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext): if lhs and part: machins.append(part) part = [] part.append( ( (-1 if sign == '-' else 1) * ( int(mult) if mult else 1), Fraction(int(numer), (int(denom) if denom else 1)) ) ) machins.append(part) return machins     def tans(xs): xslen = len(xs) if xslen == 1: return tanEval(*xs[0]) aa, bb = xs[:xslen//2], xs[xslen//2:] a, b = tans(aa), tans(bb) return (a + b) / (1 - a * b)   def tanEval(coef, f): if coef == 1: return f if coef < 0: return -tanEval(-coef, f) ca = coef // 2 cb = coef - ca a, b = tanEval(ca, f), tanEval(cb, f) return (a + b) / (1 - a * b)     if __name__ == '__main__': machins = parse_eqn() #pp(machins, width=160) for machin, eqn in zip(machins, equationtext.split('\n')): ans = tans(machin) print('%5s: %s' % ( ('OK' if ans == 1 else 'ERROR'), eqn))
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.
#C.2B.2B
C++
#include <iostream>   int main() { std::cout << (int)'a' << std::endl; // prints "97" std::cout << (char)97 << std::endl; // prints "a" return 0; }