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/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 DIM A$(20,20)
20 LET A$(10,10)="1"
30 FOR Y=42 TO 23 STEP -1
40 FOR X=0 TO 19
50 PLOT X,Y
60 NEXT X
70 NEXT Y
80 UNPLOT 9,33
90 FOR I=1 TO 80
100 LET X=INT (RND*18)+2
110 LET Y=INT (RND*18)+2
120 IF A$(X,Y)="1" THEN GOTO 100
130 UNPLOT X-1,43-Y
140 IF A$(X+1,Y+1)="1" OR A$(X+1,Y)="1" OR A$(X+1,Y-1)="1" OR A$(X,Y+1)="1" OR A$(X,Y-1)="1" OR A$(X-1,Y+1)="1" OR A$(X-1,Y)="1" OR A$(X-1,Y-1)="1" THEN GOTO 230
150 PLOT X-1,43-Y
160 LET X=X+INT (RND*3)-1
170 LET Y=Y+INT (RND*3)-1
180 IF X=1 THEN LET X=19
190 IF X=20 THEN LET X=2
200 IF Y=1 THEN LET Y=19
210 IF Y=20 THEN LET Y=2
220 GOTO 130
230 LET A$(X,Y)="1"
240 NEXT I |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
set SIZE 300
image create photo brownianTree -width $SIZE -height $SIZE
interp alias {} plot {} brownianTree put white -to
brownianTree put black -to 0 0 [expr {$SIZE-1}] [expr {$SIZE-1}]
proc rnd {range} {expr {int(rand() * $range)}}
proc makeBrownianTree count {
global SIZE
# Set the seed
plot [rnd $SIZE] [rnd $SIZE]
for {set i 0} {$i<$count} {incr i} {
# Set a random particle's initial position
set px [rnd $SIZE]
set py [rnd $SIZE]
while 1 {
# Randomly choose a direction
set dx [expr {[rnd 3] - 1}]
set dy [expr {[rnd 3] - 1}]
# If we are going out of bounds...
if {$px+$dx < 0 || $px+$dx >= $SIZE || $py+$dy < 0 || $py+$dy>=$SIZE} {
# Out of bounds, so move back in
set dx [expr {[rnd 3] - 1}]
set dy [expr {[rnd 3] - 1}]
continue
}
set ox $px
set oy $py
# Move/see if we would hit anything
incr px $dx
incr py $dy
if {[lindex [brownianTree get $px $py] 0]} {
# Hit something, so plot where we were
plot $ox $oy
break
}
}
## For display while things are processing, uncomment next line
#update;puts -nonewline .;flush stdout
}
}
pack [label .l -image brownianTree]
update
makeBrownianTree 1000
brownianTree write tree.ppm |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Lua | Lua | function ShuffleArray(array)
for i=1,#array-1 do
local t = math.random(i, #array)
array[i], array[t] = array[t], array[i]
end
end
function GenerateNumber()
local digits = {1,2,3,4,5,6,7,8,9}
ShuffleArray(digits)
return digits[1] * 1000 +
digits[2] * 100 +
digits[3] * 10 +
digits[4]
end
function IsMalformed(input)
local malformed = false
if #input == 4 then
local already_used = {}
for i=1,4 do
local digit = input:byte(i) - string.byte('0')
if digit < 1 or digit > 9 or already_used[digit] then
malformed = true
break
end
already_used[digit] = true
end
else
malformed = true
end
return malformed
end
math.randomseed(os.time())
math.randomseed(math.random(2^31-1)) -- since os.time() only returns seconds
print("\nWelcome to Bulls and Cows!")
print("")
print("The object of this game is to guess the random 4-digit number that the")
print("computer has chosen. The number is generated using only the digits 1-9,")
print("with no repeated digits. Each time you enter a guess, you will score one")
print("\"bull\" for each digit in your guess that matches the corresponding digit")
print("in the computer-generated number, and you will score one \"cow\" for each")
print("digit in your guess that appears in the computer-generated number, but is")
print("in the wrong position. Use this information to refine your guesses. When")
print("you guess the correct number, you win.");
print("")
quit = false
repeat
magic_number = GenerateNumber()
magic_string = tostring(magic_number) -- Easier to do scoring with a string
repeat
io.write("\nEnter your guess (or 'Q' to quit): ")
user_input = io.read()
if user_input == 'Q' or user_input == 'q' then
quit = true
break
end
if not IsMalformed(user_input) then
if user_input == magic_string then
print("YOU WIN!!!")
else
local bulls, cows = 0, 0
for i=1,#user_input do
local find_result = magic_string:find(user_input:sub(i,i))
if find_result and find_result == i then
bulls = bulls + 1
elseif find_result then
cows = cows + 1
end
end
print(string.format("You scored %d bulls, %d cows", bulls, cows))
end
else
print("Malformed input. You must enter a 4-digit number with")
print("no repeated digits, using only the digits 1-9.")
end
until user_input == magic_string
if not quit then
io.write("\nPress <Enter> to play again or 'Q' to quit: ")
user_input = io.read()
if user_input == 'Q' or user_input == 'q' then
quit = true
end
end
if quit then
print("\nGoodbye!")
end
until quit |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Groovy | Groovy | def caesarEncode(cipherKey, text) {
def builder = new StringBuilder()
text.each { character ->
int ch = character[0] as char
switch(ch) {
case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break
case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break
}
builder << (ch as char)
}
builder as String
}
def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Oforth | Oforth | a b c f |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Ol | Ol |
; note: sign "==>" indicates expected output
;;; Calling a function that requires no arguments
(define (no-args-function)
(print "ok."))
(no-args-function)
; ==> ok.
;;; Calling a function with a fixed number of arguments
(define (two-args-function a b)
(print "a: " a)
(print "b: " b))
(two-args-function 8 13)
; ==> a: 8
; ==> b: 13
;;; Calling a function with optional arguments
(define (optional-args-function a . args)
(print "a: " a)
(if (null? args)
(print "no optional arguments"))
(if (less? 0 (length args))
(print "b: " (car args)))
(if (less? 1 (length args))
(print "c: " (cadr args)))
; etc...
)
(optional-args-function 3)
; ==> a: 3
; ==> no optional arguments
(optional-args-function 3 8)
; ==> a: 3
; ==> b: 8
(optional-args-function 3 8 13)
; ==> a: 3
; ==> b: 8
; ==> c: 13
(optional-args-function 3 8 13 77)
; ==> a: 3
; ==> b: 8
; ==> c: 13
;;; Calling a function with a variable number of arguments
; /same as optional arguments
;;; Calling a function with named arguments
; /no named arguments "from the box" is provided, but it can be easily simulated using builtin associative arrays (named "ff")
(define (named-args-function args)
(print "a: " (get args 'a 8)) ; 8 is default value if no variable value given
(print "b: " (get args 'b 13)); same as above
)
(named-args-function #empty)
; ==> a: 8
; ==> b: 13
(named-args-function (list->ff '((a . 3))))
; ==> a: 3
; ==> b: 13
; or nicer (and shorter) form available from ol version 2.1
(named-args-function '{a 3})
; ==> a: 3
; ==> b: 13
(named-args-function '{b 7})
; ==> a: 8
; ==> b: 7
(named-args-function '{a 3 b 7})
; ==> a: 3
; ==> b: 7
;;; Using a function in first-class context within an expression
(define (first-class-arg-function arg a b)
(print (arg a b))
)
(first-class-arg-function + 2 3)
; ==> 5
(first-class-arg-function - 2 3)
; ==> -1
;;; Using a function in statement context
(let ((function (lambda (x) (* x x))))
(print (function 4))
; ==> 16
;(print (function 4))
; ==> What is 'function'?
;;; Obtaining the return value of a function
(define (return-value-function)
(print "ok.")
123)
(let ((result (return-value-function)))
(print result))
; ==> ok.
; ==> 123
;;; Obtaining the return value of a function while breaking the function execution (for example infinite loop)
(print
(call/cc (lambda (return)
(let loop ((n 0))
(if (eq? n 100)
(return (* n n)))
(loop (+ n 1))))))) ; this is infinite loop
; ==> 10000
;;; Is partial application possible and how
(define (make-partial-function n)
(lambda (x y)
(print (n x y)))
)
(define plus (make-partial-function +))
(define minus (make-partial-function -))
(plus 2 3)
; ==> 5
(minus 2 3)
; ==> -1
;;; Distinguishing built-in functions and user-defined functions
; ol has no builtin functions but only eight builtin forms: quote, values, lambda, setq, letq, ifeq, either, values-apply.
; all other functions is "user-defined", and some of them defined in base library, for example (scheme core) defines if, or, and, zero?, length, append...
;;; Distinguishing subroutines and functions
; Both subroutines and functions is a functions in Ol.
; Btw, the "subroutine" has a different meaning in Ol - the special function that executes simultaneously in own context. The intersubroutine messaging mechanism is provided, sure.
;;; Stating whether arguments are passed by value or by reference
; The values in Ol always passed as values and objects always passed as references. If you want to pass an object copy - make a copy by yourself.
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Raku | Raku | constant Catalan = 1, { [+] @_ Z* @_.reverse } ... *; |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Python | Python | >>> import calendar
>>> help(calendar.prcal)
Help on method pryear in module calendar:
pryear(self, theyear, w=0, l=0, c=6, m=3) method of calendar.TextCalendar instance
Print a years calendar.
>>> calendar.prcal(1969)
1969
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30
31
April May June
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 4 1
7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
30
July August September
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30
October November December
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 1 2 1 2 3 4 5 6 7
6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
27 28 29 30 31 24 25 26 27 28 29 30 29 30 31 |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #TI-83_BASIC | TI-83 BASIC | :StoreGDB 0
:ClrDraw
:FnOff
:AxesOff
:Pxl-On(31,47)
:For(I,1,50)
:randInt(1,93)→X
:randInt(1,61)→Y
:1→A
:While A
:randInt(1,4)→D
:Pxl-Off(Y,X)
:If D=1 and Y≥2
:Y-1→Y
:If D=2 and X≤92
:X+1→X
:If D=3 and Y≤60
:Y+1→Y
:If D=4 and X≥2
:X-1→X
:Pxl-On(Y,X)
:If pxl-Test(Y+1,X) or pxl-Test(Y+1,X+1) or pxl-Test(Y+1,X-1) or pxl-Test(Y,X+1) or pxl-Test(Y,X-1) or pxl-Test(Y-1,X) or pxl-Test(Y-1,X-1) or pxl-Test(Y-1,X+1)
:0→A
:End
:End
:Pause
:RecallGDB 0 |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Visual_Basic_.NET | Visual Basic .NET |
Imports System.Drawing.Imaging
Public Class Form1
ReadOnly iCanvasColor As Integer = Color.Black.ToArgb
ReadOnly iSeedColor As Integer = Color.White.ToArgb
Dim iCanvasWidth As Integer = 0
Dim iCanvasHeight As Integer = 0
Dim iPixels() As Integer = Nothing
Private Sub BrownianTree()
Dim oCanvas As Bitmap = Nothing
Dim oRandom As New Random(Now.Millisecond)
Dim oXY As Point = Nothing
Dim iParticleCount As Integer = 0
iCanvasWidth = ClientSize.Width
iCanvasHeight = ClientSize.Height
oCanvas = New Bitmap(iCanvasWidth, iCanvasHeight, Imaging.PixelFormat.Format24bppRgb)
Graphics.FromImage(oCanvas).Clear(Color.FromArgb(iCanvasColor))
iPixels = GetData(oCanvas)
' We'll use about 10% of the total number of pixels in the canvas for the particle count.
iParticleCount = CInt(iPixels.Length * 0.1)
' Set the seed to a random location on the canvas.
iPixels(oRandom.Next(iPixels.Length)) = iSeedColor
' Run through the particles.
For i As Integer = 0 To iParticleCount
Do
' Find an open pixel.
oXY = New Point(oRandom.Next(oCanvas.Width), oRandom.Next(oCanvas.Height))
Loop While iPixels(oXY.Y * oCanvas.Width + oXY.X) = iSeedColor
' Jitter until the pixel bumps another.
While Not CheckAdjacency(oXY)
oXY.X += oRandom.Next(-1, 2)
oXY.Y += oRandom.Next(-1, 2)
' Make sure we don't jitter ourselves out of bounds.
If oXY.X < 0 Then oXY.X = 0 Else If oXY.X >= oCanvas.Width Then oXY.X = oCanvas.Width - 1
If oXY.Y < 0 Then oXY.Y = 0 Else If oXY.Y >= oCanvas.Height Then oXY.Y = oCanvas.Height - 1
End While
iPixels(oXY.Y * oCanvas.Width + oXY.X) = iSeedColor
' If you'd like to see updates as each particle collides and becomes
' part of the tree, uncomment the next 4 lines (it does slow it down slightly).
' SetData(oCanvas, iPixels)
' BackgroundImage = oCanvas
' Invalidate()
' Application.DoEvents()
Next
oCanvas.Save("BrownianTree.bmp")
BackgroundImage = oCanvas
End Sub
' Check adjacent pixels for an illuminated pixel.
Private Function CheckAdjacency(ByVal XY As Point) As Boolean
Dim n As Integer = 0
For y As Integer = -1 To 1
' Make sure not to drop off the top or bottom of the image.
If (XY.Y + y < 0) OrElse (XY.Y + y >= iCanvasHeight) Then Continue For
For x As Integer = -1 To 1
' Make sure not to drop off the left or right of the image.
If (XY.X + x < 0) OrElse (XY.X + x >= iCanvasWidth) Then Continue For
' Don't run the test on the calling pixel.
If y <> 0 AndAlso x <> 0 Then
n = (XY.Y + y) * iCanvasWidth + (XY.X + x)
If iPixels(n) = iSeedColor Then Return True
End If
Next
Next
Return False
End Function
Private Function GetData(ByVal Map As Bitmap) As Integer()
Dim oBMPData As BitmapData = Nothing
Dim oData() As Integer = Nothing
oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oData, Map.Width * Map.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oData, 0, oData.Length)
Map.UnlockBits(oBMPData)
Return oData
End Function
Private Sub SetData(ByVal Map As Bitmap, ByVal Data As Integer())
Dim oBMPData As BitmapData = Nothing
oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(Data, 0, oBMPData.Scan0, Data.Length)
Map.UnlockBits(oBMPData)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DoubleBuffered = True
BackgroundImageLayout = ImageLayout.Center
Show()
Activate()
Application.DoEvents()
BrownianTree()
End Sub
End Class
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #M2000_Interpreter | M2000 Interpreter |
Module Game {
Malformed=lambda (a$)->{
=true
if len(a$)<>4 then exit
n=0 : dummy=val(a$,"int",n)
if n<>5 or dummy=0 then exit
for i=1 to 9
if len(filter$(a$,str$(i,0)))<3 then break
next i
=false
}
BullsAndCows$=lambda$ (a$, b$, &ok) ->{
Def b, c
for i=1 to 4
if mid$(a$,i,1)=mid$(b$,i,1) then
b++
else.if instr(b$,mid$(a$,i,1))>0 then
c++
end if
next i
ok=b=4
=format$("bulls {0}, cows {1}", b, c)
}
Random$=lambda$ ->{
def repl$, bank$, c$
bank$="123456789"
for i=1 to 4
c$=mid$(bank$,random(1,len(bank$)),1)
bank$=filter$(bank$, c$)
repl$+=c$
next i
=repl$
}
target$=Random$()
def boolean win=false, a$
do
do
Input "Next guess ";a%
a$=str$(a%,0)
if Malformed(a$) then Print "Malformed input, try again" else exit
always
Print BullsAndCows$(a$, target$, &win)
if win then exit
Print "Bad guess! (4 unique digits, 1-9)"
always
Print "You guess it"
}
Game
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Haskell | Haskell | module Caesar (caesar, uncaesar) where
import Data.Char
caesar, uncaesar :: (Integral a) => a -> String -> String
caesar k = map f
where f c = case generalCategory c of
LowercaseLetter -> addChar 'a' k c
UppercaseLetter -> addChar 'A' k c
_ -> c
uncaesar k = caesar (-k)
addChar :: (Integral a) => Char -> a -> Char -> Char
addChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)
where b' = fromIntegral $ ord b
c' = fromIntegral $ ord c
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #ooRexx | ooRexx | say 'DATE'()
Say date()
Exit
daTe: Return 'my date' |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #REXX | REXX | /*REXX program calculates and displays Catalan numbers using four different methods. */
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then do; HI=15; LO=0; end /*No args? Then use a range of 0 ──► 15*/
if HI=='' | HI=="," then HI=LO /*No HI? Then use LO for the default*/
numeric digits max(20, 5*HI) /*this allows gihugic Catalan numbers. */
w=length(HI) /*W: is used for aligning the output. */
call hdr 1A; do j=LO to HI; say ' Catalan' right(j, w)": " Cat1A(j); end
call hdr 1B; do j=LO to HI; say ' Catalan' right(j, w)": " Cat1B(j); end
call hdr 2 ; do j=LO to HI; say ' Catalan' right(j, w)": " Cat2(j) ; end
call hdr 3 ; do j=LO to HI; say ' Catalan' right(j, w)": " Cat3(j) ; end
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: arg z; if !.z\==. then return !.z; !=1; do k=2 to z; !=!*k; end; !.z=!; return !
Cat1A: procedure expose !.; parse arg n; return comb(n+n, n) % (n+1)
Cat1B: procedure expose !.; parse arg n; return !(n+n) % ((n+1) * !(n)**2)
Cat3: procedure expose c.; arg n; if c.n==. then c.n=(4*n-2)*cat3(n-1)%(n+1); return c.n
comb: procedure; parse arg x,y; return pFact(x-y+1, x) % pFact(2, y)
hdr: !.=.; c.=.; c.0=1; say; say center('Catalan numbers, method' arg(1),79,'─'); return
pFact: procedure; !=1; do k=arg(1) to arg(2); !=!*k; end; return !
/*──────────────────────────────────────────────────────────────────────────────────────*/
Cat2: procedure expose c.; parse arg n; $=0; if c.n\==. then return c.n
do k=0 for n; $=$ + Cat2(k) * Cat2(n-k-1); end
c.n=$; return $ /*use a memoization technique.*/ |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Racket | Racket | #lang racket
(require racket/date net/base64 file/gunzip)
(define (calendar yr)
(define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n)))))
(define months
(for/list ([mn (in-naturals 1)]
[mname '(January February March April May June July
August September October November December)])
(define s (find-seconds 0 0 12 1 mn yr))
(define pfx (date-week-day (seconds->date s)))
(define days
(let ([? (if (= mn 12) (λ(x y) y) (λ(x y) x))])
(round (/ (- (find-seconds 0 0 12 1 (? (+ 1 mn) 1) (? yr (+ 1 yr))) s)
60 60 24))))
(list* (~a mname #:width 20 #:align 'center) "Su Mo Tu We Th Fr Sa"
(map string-join
(nsplit 7 `(,@(make-list pfx " ")
,@(for/list ([d days])
(~a (+ d 1) #:width 2 #:align 'right))
,@(make-list (- 42 pfx days) " ")))))))
(let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP
sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj
ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="]
[o (open-output-string)])
(inflate (open-input-bytes (base64-decode s)) o)
(display (regexp-replace #rx"~a" (get-output-string o) (~a yr))))
(for-each displayln
(dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)])
(regexp-replace #rx" +$" (string-join s " ") ""))
(λ(s) (equal? "" s)))))
(calendar 1969) |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
var Rand = Random.new()
var N8 = [
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1]
]
class BrownianTree {
construct new(width, height, particles) {
Window.title = "Brownian Tree"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_n = particles
}
init() {
Canvas.cls(Color.brown)
// off center seed position makes pleasingly asymetrical tree
Canvas.pset(_w/3, _h/3, Color.white)
var x = 0
var y = 0
var a = 0
while (a < _n) {
// generate random position for new particle
x = Rand.int(_w)
y = Rand.int(_h)
var outer = false
var p = Canvas.pget(x, y)
if (p == Color.white) {
// as position is already set, find a nearby free position.
while (p == Color.white) {
x = x + Rand.int(3) - 1
y = y + Rand.int(3) - 1
var ok = x >= 0 && x < _w && y >= 0 && y < _h
if (ok) {
p = Canvas.pget(x, y)
} else { // out of bounds, consider particle lost
outer = true
a = a + 1
break
}
}
} else {
// else particle is in free space
// let it wonder until it touches tree
while (!hasNeighbor(x, y)) {
x = x + Rand.int(3) - 1
y = y + Rand.int(3) - 1
var ok = x >= 0 && x < _w && y >= 0 && y < _h
if (ok) {
p = Canvas.pget(x, y)
} else { // out of bounds, consider particle lost
outer = true
a = a + 1
break
}
}
}
if (outer) continue
// x, y now specify a free position touching the tree
Canvas.pset(x, y, Color.white)
a = a + 1
// progress indicator
if (a % 100 == 0) System.print("%(a) of %(_n)")
a = a + 1
}
}
hasNeighbor(x, y) {
for (n in N8) {
var xn = x + n[0]
var yn = y + n[1]
var ok = xn >= 0 && xn < _w && yn >= 0 && yn < _h
if (ok && Canvas.pget(xn, yn) == Color.white) return true
}
return false
}
update() {}
draw(alpha) {}
}
var Game = BrownianTree.new(200, 150, 7500) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Maple | Maple | BC := proc(n) #where n is the number of turns the user wishes to play before they quit
local target, win, numGuesses, guess, bulls, cows, i, err;
target := [0, 0, 0, 0]:
randomize(); #This is a command that makes sure that the numbers are truly randomized each time, otherwise your first time will always give the same result.
while member(0, target) or numelems({op(target)}) < 4 do #loop continues to generate random numbers until you get one with no repeating digits or 0s
target := [seq(parse(i), i in convert(rand(1234..9876)(), string))]: #a list of random numbers
end do:
win := false:
numGuesses := 0:
while win = false and numGuesses < n do #loop allows the user to play until they win or until a set amount of turns have passed
err := true;
while err do #loop asks for values until user enters a valid number
printf("Please enter a 4 digit integer with no repeating digits\n");
try#catches any errors in user input
guess := [seq(parse(i), i in readline())];
if hastype(guess, 'Not(numeric)', 'exclude_container') then
printf("Postive integers only! Please guess again.\n\n");
elif numelems(guess) <> 4 then
printf("4 digit numbers only! Please guess again.\n\n");
elif numelems({op(guess)}) < 4 then
printf("No repeating digits! Please guess again.\n\n");
elif member(0, guess) then
printf("No 0s! Please guess again.\n\n");
else
err := false;
end if;
catch:
printf("Invalid input. Please guess again.\n\n");
end try;
end do:
numGuesses := numGuesses + 1;
printf("Guess %a: %a\n", numGuesses, guess);
bulls := 0;
cows := 0;
for i to 4 do #loop checks for bulls and cows in the user's guess
if target[i] = guess[i] then
bulls := bulls + 1;
elif member(target[i], guess) then
cows := cows + 1;
end if;
end do;
if bulls = 4 then
win := true;
printf("The number was %a.\n", target);
printf(StringTools[FormatMessage]("You won with %1 %{1|guesses|guess|guesses}.", numGuesses));
else
printf(StringTools[FormatMessage]("%1 %{1|Cows|Cow|Cows}, %2 %{2|Bulls|Bull|Bulls}.\n\n", cows, bulls));
end if;
end do:
if win = false and numGuesses >= n then
printf("You lost! The number was %a.\n", target);
end if;
return NULL;
end proc: |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Hoon | Hoon | |%
++ enc
|= [msg=tape key=@ud]
^- tape
(turn `(list @)`msg |=(n=@ud (add (mod (add (sub n 'A') key) 26) 'A')))
++ dec
|= [msg=tape key=@ud]
(enc msg (sub 26 key))
-- |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #PARI.2FGP | PARI/GP | f(); \\ zero arguments
sin(Pi/2); \\ fixed number of arguments
vecsort([5,6]) != vecsort([5,6],,4) \\ optional arguments
Str("gg", 1, "hh") \\ variable number of arguments
call(Str, ["gg", 1, "hh"]) \\ variable number of arguments in a vector
(x->x^2)(3); \\ first-class
x = sin(0); \\ get function value |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Ring | Ring |
for n = 1 to 15
see catalan(n) + nl
next
func catalan n
if n = 0 return 1 ok
cat = 2 * (2 * n - 1) * catalan(n - 1) / (n + 1)
return cat
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Raku | Raku | my $months-per-row = 3;
my @weekday-names = <Mo Tu We Th Fr Sa Su>;
my @month-names = <Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec>;
my Int() $year = @*ARGS.shift || 1969;
say fmt-year($year);
sub fmt-year ($year) {
my @month-strs;
@month-strs[$_] = [fmt-month($year, $_).lines] for 1 .. 12;
my @C = ' ' x 30 ~ $year, '';
for 1, 1+$months-per-row ... 12 -> $month {
while @month-strs[$month] {
for ^$months-per-row -> $column {
@C[*-1] ~= @month-strs[$month+$column].shift ~ ' ' x 3 if @month-strs[$month+$column];
}
@C.push: '';
}
@C.push: '';
}
@C.join: "\n";
}
sub fmt-month ($year, $month) {
my $date = Date.new($year,$month,1);
@month-names[$month-1].fmt("%-20s\n") ~ @weekday-names ~ "\n" ~
((' ' xx $date.day-of-week - 1), (1..$date.days-in-month)».fmt('%2d')).flat.rotor(7, :partial).join("\n") ~
(' ' if $_ < 7) ~ (' ' xx 7-$_).join(' ') given Date.new($year, $month, $date.days-in-month).day-of-week;
} |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def W=128, H=W; \width and height of field
int X, Y;
[SetVid($13); \set 320x200 graphic video mode
Point(W/2, H/2, 6\brown\); \place seed in center of field
loop [repeat X:= Ran(W); Y:= Ran(H); \inject particle
until ReadPix(X,Y) = 0; \ in an empty location
loop [Point(X, Y, 6\brown\); \show particle
if ReadPix(X-1,Y) or ReadPix(X+1,Y) or \particle collided
ReadPix(X,Y-1) or ReadPix(X,Y+1) then quit;
Point(X, Y, 0\black\); \erase particle
X:= X + Ran(3)-1; \(Brownian) move particle
Y:= Y + Ran(3)-1;
if X<0 or X>=W or Y<0 or Y>=H then quit; \out of bounds
];
if KeyHit then [SetVid(3); quit]; \restore text mode
];
] |
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #zkl | zkl | w:=h:=400; numParticles:=20_000;
bitmap:=PPM(w+2,h+2,0); // add borders as clip regions
bitmap[w/2,h/2]=0xff|ff|ff; // plant seed
bitmap.circle(w/2,h/2,h/2,0x0f|0f|0f); // plant seeds
fcn touching(x,y,bitmap){ // is (x,y) touching another pixel?
// (x,y) isn't on the border/edge of bitmap so no edge conditions
var [const] box=T(T(-1,-1),T(0,-1),T(1,-1),
T(-1, 0), T(1, 0),
T(-1, 1),T(0, 1),T(1, 1));
box.filter1('wrap([(a,b)]){ bitmap[a+x,b+y] }); //-->False: not touching, (a,b) if is
}
while(numParticles){
c:=(0x1|00|00).random(0x1|00|00|00) + (0x1|00).random(0x1|00|00) + (0x1).random(0x1|00);
reg x,y;
do{ x=(1).random(w); y=(1).random(h); }while(bitmap[x,y]); // find empty spot
while(1){ // stagger around until bump into a particle, then attach barnicle
if(touching(x,y,bitmap)){
bitmap[x,y]=c;
bitmap.write(f:=File("brownianTree.zkl.ppm","wb")); // tell ImageViewer to update image
numParticles-=1;
break;
}
x+=(-1).random(2); y+=(-1).random(2); // [-1,0,1]
if( not ((0<x<w) and (0<y<h)) ){ // next to border --> color border
bitmap[x,y]=c;
break;
}
}
}
bitmap.writeJPGFile("brownianTree.zkl.jpg"); // the final image |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
codes=ToCharacterCode[StringJoin[ToString/@digits]];
Module[{r,bulls,cows},
While[True,
r=InputString[];
If[r===$Canceled,Break[],
With[{userCodes=ToCharacterCode@r},
If[userCodes===codes,Print[r<>": You got it!"];Break[],
If[Length@userCodes==Length@codes,
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
Print["Guess four digits."]]]]]]] |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Icon_and_Unicon | Icon and Unicon | procedure main()
ctext := caesar(ptext := map("The quick brown fox jumped over the lazy dog"))
dtext := caesar(ctext,,"decrypt")
write("Plain text = ",image(ptext))
write("Encphered text = ",image(ctext))
write("Decphered text = ",image(dtext))
end
procedure caesar(text,k,mode) #: mono-alphabetic shift cipher
/k := 3
k := (((k % *&lcase) + *&lcase) % *&lcase) + 1
case mode of {
&null|"e"|"encrypt": return map(text,&lcase,(&lcase||&lcase)[k+:*&lcase])
"d"|"decrypt" : return map(text,(&lcase||&lcase)[k+:*&lcase],&lcase)
}
end |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Pascal | Pascal | foo |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Perl | Perl | foo(); # Call foo on the null list
&foo(); # Ditto
foo($arg1, $arg2); # Call foo on $arg1 and $arg2
&foo($arg1, $arg2); # Ditto; ignores prototypes |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Ruby | Ruby | def factorial(n)
(1..n).reduce(1, :*)
end
# direct
def catalan_direct(n)
factorial(2*n) / (factorial(n+1) * factorial(n))
end
# recursive
def catalan_rec1(n)
return 1 if n == 0
(0...n).inject(0) {|sum, i| sum + catalan_rec1(i) * catalan_rec1(n-1-i)}
end
def catalan_rec2(n)
return 1 if n == 0
2*(2*n - 1) * catalan_rec2(n-1) / (n+1)
end
# performance and results
require 'benchmark'
require 'memoize'
include Memoize
Benchmark.bm(17) do |b|
b.report('catalan_direct') {16.times {|n| catalan_direct(n)} }
b.report('catalan_rec1') {16.times {|n| catalan_rec1(n)} }
b.report('catalan_rec2') {16.times {|n| catalan_rec2(n)} }
memoize :catalan_rec1
b.report('catalan_rec1(memo)'){16.times {|n| catalan_rec1(n)} }
end
puts "\n direct rec1 rec2"
16.times {|n| puts "%2d :%9d%9d%9d" % [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Rebol | Rebol |
do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year]
foreach m system/locale/months [
prin rejoin ["^/^/ " m "^/^/ "]
foreach day system/locale/days [prin join copy/part day 2 " "]
print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "]
repeat i 31 [
if attempt [c: to-date rejoin [i"-"m"-"y]][
prin join either 1 = length? form i [" "][" "] i
if c/weekday = 7 [print ""]
]
]
] ask "^/^/Press [ENTER] to Continue..."]
|
http://rosettacode.org/wiki/Brownian_tree | Brownian tree | Brownian tree
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw a Brownian Tree.
A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.
The initial "seed" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.
Particles are injected into the field, and are individually given a (typically random) motion pattern.
When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.
Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET np=1000
20 PAPER 0: INK 4: CLS
30 PLOT 128,88
40 FOR i=1 TO np
50 GO SUB 1000
60 IF NOT ((POINT (x+1,y+1)+POINT (x,y+1)+POINT (x+1,y)+POINT (x-1,y-1)+POINT (x-1,y)+POINT (x,y-1))=0) THEN GO TO 100
70 LET x=x+RND*2-1: LET y=y+RND*2-1
80 IF x<1 OR x>254 OR y<1 OR y>174 THEN GO SUB 1000
90 GO TO 60
100 PLOT x,y
110 NEXT i
120 STOP
1000 REM Calculate new pos
1010 LET x=RND*254
1020 LET y=RND*174
1030 RETURN
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #MATLAB | MATLAB | function BullsAndCows
% Plays the game Bulls and Cows as the "game master"
% Create a secret number
nDigits = 4;
lowVal = 1;
highVal = 9;
digitList = lowVal:highVal;
secret = zeros(1, 4);
for k = 1:nDigits
idx = randi(length(digitList));
secret(k) = digitList(idx);
digitList(idx) = [];
end
% Give game information
fprintf('Welcome to Bulls and Cows!\n')
fprintf('Try to guess the %d-digit number (no repeated digits).\n', nDigits)
fprintf('Digits are between %d and %d (inclusive).\n', lowVal, highVal)
fprintf('Score: 1 Bull per correct digit in correct place.\n')
fprintf(' 1 Cow per correct digit in incorrect place.\n')
fprintf('The number has been chosen. Now it''s your moooooove!\n')
gs = input('Guess: ', 's');
% Loop until user guesses right or quits (no guess)
nGuesses = 1;
while gs
gn = str2double(gs);
if isnan(gn) || length(gn) > 1 % Not a scalar
fprintf('Malformed guess. Keep to valid scalars.\n')
gs = input('Try again: ', 's');
else
g = sprintf('%d', gn) - '0';
if length(g) ~= nDigits || any(g < lowVal) || any(g > highVal) || ...
length(unique(g)) ~= nDigits % Invalid number for game
fprintf('Malformed guess. Remember:\n')
fprintf(' %d digits\n', nDigits)
fprintf(' Between %d and %d inclusive\n', lowVal, highVal)
fprintf(' No repeated digits\n')
gs = input('Try again: ', 's');
else
score = CountBullsCows(g, secret);
if score(1) == nDigits
fprintf('You win! Bully for you! Only %d guesses.\n', nGuesses)
gs = '';
else
fprintf('Score: %d Bulls, %d Cows\n', score)
gs = input('Guess: ', 's');
end
end
end
nGuesses = nGuesses+1; % Counts malformed guesses
end
end
function score = CountBullsCows(guess, correct)
% Checks the guessed array of digits against the correct array to find the score
% Assumes arrays of same length and valid numbers
bulls = guess == correct;
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #IS-BASIC | IS-BASIC | 100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
130 DO
140 INPUT PROMPT "Key (1-25): ":KEY
150 LOOP UNTIL KEY>0 AND KEY<26
160 PRINT "Original message: ";M$
170 CALL ENCRYPT(M$,KEY)
180 PRINT "Encrypted message: ";M$
190 CALL DECRYPT(M$,KEY)
200 PRINT "Decrypted message: ";M$
210 DEF ENCRYPT(REF M$,KEY)
220 STRING T$*254
230 LET T$=""
240 FOR I=1 TO LEN(M$)
250 SELECT CASE M$(I)
260 CASE "A" TO "Z"
270 LET T$=T$&CHR$(65+MOD(ORD(M$(I))-65+KEY,26))
280 CASE "a" TO "z"
290 LET T$=T$&CHR$(97+MOD(ORD(M$(I))-97+KEY,26))
300 CASE ELSE
310 LET T$=T$&M$(I)
320 END SELECT
330 NEXT
340 LET M$=T$
350 END DEF
360 DEF DECRYPT(REF M$,KEY)
370 STRING T$*254
380 LET T$=""
390 FOR I=1 TO LEN(M$)
400 SELECT CASE M$(I)
410 CASE "A" TO "Z"
420 LET T$=T$&CHR$(65+MOD(ORD(M$(I))-39-KEY,26))
430 CASE "a" TO "z"
440 LET T$=T$&CHR$(97+MOD(ORD(M$(I))-71-KEY,26))
450 CASE ELSE
460 LET T$=T$&M$(I)
470 END SELECT
480 NEXT
490 LET M$=T$
500 END DEF |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Phix | Phix | {} = myfunction()
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Phixmonti | Phixmonti | def saludo
"Hola mundo" print nl
enddef
saludo
getid saludo exec |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Run_BASIC | Run BASIC | FOR i = 1 TO 15
PRINT i;" ";catalan(i)
NEXT
FUNCTION catalan(n)
catalan = 1
if n <> 0 then catalan = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1)
END FUNCTION |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #REXX | REXX | 11 9999999 6666666 9999999
111 999999999 666666666 999999999
1111 99 99 66 66 99 99
11 99 99 66 99 99
11 99 999 66 99 999
11 999999999 66 666666 999999999
11 99999 99 6666666666 99999 99
11 99 666 66 99
11 99 66 66 99
11 99 99 66 66 99 99
111111 99999999 66666666 99999999
111111 999999 666666 999999
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #MAXScript | MAXScript |
numCount = 4 -- number of digits to use
digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
num = ""
while num.count < numCount and digits.count > 0 do
(
local r = random 1 digits.count
append num (digits[r] as string)
deleteitem digits r
)
digits = undefined
numGuesses = 0
inf = "Rules: \n1. Choose only % unique digits in any combination"+\
" (0 can't be used).\n2. Only positive integers are allowed."+\
"\n3. For each digit that is in it's place, you get a bull,\n"+\
"\tand for each digit that is not in it's place, you get a cow."+\
"\n4. The game is won when your number matches the number I chose."+\
"\n\nPress [esc] to quit the game.\n\n"
clearlistener()
format inf num.count
while not keyboard.escpressed do
(
local userVal = getkbvalue prompt:"\nEnter your number: "
if (userVal as string) == num do
(
format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses
exit with OK
)
local bulls = 0
local cows = 0
local badInput = false
case of
(
(classof userVal != integer):
(
format "\nThe number must be a positive integer.\n"
badInput = true
)
((userVal as string).count != num.count):
(
format "\nThe number must have % digits.\n" num.count
badInput = true
)
((makeuniquearray (for i in 1 to (userVal as string).count \
collect (userVal as string)[i])).count != (userVal as string).count):
(
format "\nThe number can only have unique digits.\n"
badInput = true
)
)
if not badInput do
(
userVal = userVal as string
i = 1
while i <= userVal.count do
(
for j = 1 to num.count do
(
if userVal[i] == num[j] do
(
if i == j then bulls += 1 else cows += 1
)
)
i += 1
)
numGuesses += 1
format "\nBulls: % Cows: %\n" bulls cows
)
) |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #J | J | cndx=: [: , 65 97 +/ 26 | (i.26)&+
caesar=: (cndx 0)}&a.@u:@cndx@[ {~ a.i.] |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #PicoLisp | PicoLisp | (foo)
(bar 1 'arg 2 'mumble) |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #PureBasic | PureBasic | Procedure Saludo()
PrintN("Hola mundo!")
EndProcedure
Procedure.s Copialo(txt.s, siNo.b, final.s = "")
Define nuevaCadena.s, resul.s
For cont.b = 1 To siNo
nuevaCadena + txt
Next
Resul = Trim(nuevaCadena) + final
ProcedureReturn resul
EndProcedure
Procedure testNumeros(a.i, b.i, c.i = 0)
PrintN(Str(a) + #TAB$ + Str(b) + #TAB$ + Str(c))
EndProcedure
Procedure testCadenas(txt.s)
For cont.b = 1 To Len(txt)
Print(Mid(txt,cont,1))
Next cont
EndProcedure
OpenConsole()
Saludo()
PrintN(Copialo("Saludos ", 6))
PrintN(Copialo("Saludos ", 3, "!!"))
PrintN("")
testNumeros(1, 2, 3)
testNumeros(1, 2)
PrintN("")
testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
Input()
CloseConsole() |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Rust | Rust | fn c_n(n: u64) -> u64 {
match n {
0 => 1,
_ => c_n(n - 1) * 2 * (2 * n - 1) / (n + 1)
}
}
fn main() {
for i in 1..16 {
println!("c_n({}) = {}", i, c_n(i));
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Ring | Ring |
# Project : Calendar
load "guilib.ring"
load "stdlib.ring"
new qapp
{
win1 = new qwidget() {
day = list(12)
pos = newlist(12,37)
month = list(12)
week = list(7)
weekday = list(7)
button = newlist(7,6)
monthsnames = list(12)
week = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"]
daysnew = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]]
mo = [4,0,0,3,5,1,3,6,2,4,0,2]
mon = [31,28,31,30,31,30,31,31,30,31,30,31]
m2 = (((1969-1900)%7) + floor((1969 - 1900)/4) % 7) % 7
for n = 1 to 12
month[n] = (mo[n] + m2) % 7
x = (month[n] + 1) % 7 + 1
for m = 1 to len(daysnew)
if daysnew[m][1] = x
nr = m
ok
next
day[n] = daysnew[nr][2]
next
for m = 1 to 12
for n = 1 to day[m] - 1
pos[m][n] = " "
next
next
for m = 1 to 12
for n = day[m] to 37
if n < (mon[m] + day[m])
pos[m][n] = n - day[m] + 1
else
pos[m][n] = " "
ok
next
next
setwindowtitle("Calendar")
setgeometry(100,100,650,800)
label1 = new qlabel(win1) {
setgeometry(10,10,800,600)
settext("")
}
year = new qpushbutton(win1)
{
setgeometry(280,20,60,20)
year.settext("1969")
}
for n = 1 to 4
nr = (n-1)*3+1
showmonths(nr)
next
for n = 1 to 12
showweeks(n)
next
for n = 1 to 12
showdays(n)
next
show()
}
exec()
}
func showmonths(m)
for n = m to m + 2
monthsnames[n] = new qpushbutton(win1)
{
if n%3 = 1
col = 120
rownr = floor(n/3)
if rownr = 0
rownr = n/3
ok
if n = 1
row = 40
else
row = 40+rownr*180
ok
else
colnr = n%3
if colnr = 0
colnr = 3
ok
rownr = floor(n/3)
if n%3 = 0
rownr = floor(n/3)-1
ok
col = 120 + (colnr-1)*160
row = 40 + rownr*180
ok
setgeometry(col,row,60,20)
monthsnames[n].settext(months[n])
}
next
func showweeks(n)
for m = 1 to 7
col = m%7
if col = 0 col = 7 ok
weekday[m] = new qpushbutton(win1)
{
colnr = n % 3
if colnr = 0
colnr = 3
ok
rownr = floor(n/3)
if n%3 = 0
rownr = floor(n/3)-1
ok
colbegin = 60 + (colnr-1)*160
rowbegin = 60 + (rownr)*180
setgeometry(colbegin+col*20,rowbegin,20,20)
weekday[m].settext(week[m])
}
next
func showdays(ind)
rownr = floor(ind/3)
if ind%3 = 0
rownr = floor(ind/3)-1
ok
rowbegin = 60+rownr*180
for m = 1 to 6
for n = 1 to 7
col = n%7
if col = 0 col = 7 ok
row = m
button[n][m] = new qpushbutton(win1)
{
if ind%3 = 1
colbegin = 60
elseif ind%3 = 2
colbegin = 220
else
colbegin = 380
ok
setgeometry(colbegin+col*20,rowbegin+row*20,20,20)
nr = (m-1)*7+n
if nr <= 37
if pos[ind][nr] != " "
button[n][m].settext(string(pos[ind][nr]))
ok
ok
}
next
next
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #MiniScript | MiniScript | secret = range(1,9)
secret.shuffle
secret = secret[:4].join("")
while true
guess = input("Your guess? ").split("")
if guess.len != 4 then
print "Please enter 4 numbers, with no spaces."
continue
end if
bulls = 0
cows = 0
for i in guess.indexes
if secret[i] == guess[i] then
bulls = bulls + 1
else if secret.indexOf(guess[i]) != null then
cows = cows + 1
end if
end for
if bulls == 4 then
print "You got it! Great job!"
break
end if
print "You score " + bulls + " bull" + "s"*(bulls!=1) +
" and " + cows + " cow" + "s"*(cows!=1) + "."
end while |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Janet | Janet |
(def alphabet "abcdefghijklmnopqrstuvwxyz")
(defn rotate
"shift bytes given x"
[str x]
(let [r (% x (length alphabet))
b (string/bytes str)
abyte (get (string/bytes "a") 0)
zbyte (get (string/bytes "z") 0)]
(var result @[])
(for i 0 (length b)
(let [ch (bor (get b i) 0x20)] # convert uppercase to lowercase
(when (and (<= abyte ch) (<= ch zbyte))
(array/push result (get alphabet (% (+ (+ (+ (- zbyte abyte) 1) (- ch abyte)) r) (length alphabet)))))))
(string/from-bytes ;result)))
(defn code
"encodes and decodes str given argument type"
[str rot type]
(case type
:encode (rotate str rot)
:decode (rotate str (* rot -1))))
(defn main [& args]
(let [cipher (code "The quick brown fox jumps over the lazy dog" 23 :encode)
str (code cipher 23 :decode)]
(print cipher)
(print str)))
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Python | Python | def no_args():
pass
# call
no_args()
def fixed_args(x, y):
print('x=%r, y=%r' % (x, y))
# call
fixed_args(1, 2) # x=1, y=2
## Can also called them using the parameter names, in either order:
fixed_args(y=2, x=1)
## Can also "apply" fixed_args() to a sequence:
myargs=(1,2) # tuple
fixed_args(*myargs)
def opt_args(x=1):
print(x)
# calls
opt_args() # 1
opt_args(3.141) # 3.141
def var_args(*v):
print(v)
# calls
var_args(1, 2, 3) # (1, 2, 3)
var_args(1, (2,3)) # (1, (2, 3))
var_args() # ()
## Named arguments
fixed_args(y=2, x=1) # x=1, y=2
## As a statement
if 1:
no_args()
## First-class within an expression
assert no_args() is None
def return_something():
return 1
x = return_something()
def is_builtin(x):
print(x.__name__ in dir(__builtins__))
# calls
is_builtin(pow) # True
is_builtin(is_builtin) # False
# Very liberal function definition
def takes_anything(*args, **kwargs):
for each in args:
print(each)
for key, value in sorted(kwargs.items()):
print("%s:%s" % (key, value))
# Passing those to another, wrapped, function:
wrapped_fn(*args, **kwargs)
# (Function being wrapped can have any parameter list
# ... that doesn't have to match this prototype)
## A subroutine is merely a function that has no explicit
## return statement and will return None.
## Python uses "Call by Object Reference".
## See, for example, http://www.python-course.eu/passing_arguments.php
## For partial function application see:
## http://rosettacode.org/wiki/Partial_function_application#Python |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Scala | Scala |
object CatalanNumbers {
def main(args: Array[String]): Unit = {
for (n <- 0 to 15) {
println("catalan(" + n + ") = " + catalan(n))
}
}
def catalan(n: BigInt): BigInt = factorial(2 * n) / (factorial(n + 1) * factorial(n))
def factorial(n: BigInt): BigInt = BigInt(1).to(n).foldLeft(BigInt(1))(_ * _)
}
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Ruby | Ruby | require 'date'
# Creates a calendar of _year_. Returns this calendar as a multi-line
# string fit to _columns_.
def cal(year, columns)
# Start at January 1.
#
# Date::ENGLAND marks the switch from Julian calendar to Gregorian
# calendar at 1752 September 14. This removes September 3 to 13 from
# year 1752. (By fortune, it keeps January 1.)
#
date = Date.new(year, 1, 1, Date::ENGLAND)
# Collect calendars of all 12 months.
months = (1..12).collect do |month|
rows = [Date::MONTHNAMES[month].center(20), "Su Mo Tu We Th Fr Sa"]
# Make array of 42 days, starting with Sunday.
days = []
date.wday.times { days.push " " }
while date.month == month
days.push("%2d" % date.mday)
date += 1
end
(42 - days.length).times { days.push " " }
days.each_slice(7) { |week| rows.push(week.join " ") }
next rows
end
# Calculate months per row (mpr).
# 1. Divide columns by 22 columns per month, rounded down. (Pretend
# to have 2 extra columns; last month uses only 20 columns.)
# 2. Decrease mpr if 12 months would fit in the same months per
# column (mpc). For example, if we can fit 5 mpr and 3 mpc, then
# we use 4 mpr and 3 mpc.
mpr = (columns + 2).div 22
mpr = 12.div((12 + mpr - 1).div mpr)
# Use 20 columns per month + 2 spaces between months.
width = mpr * 22 - 2
# Join months into calendar.
rows = ["[Snoopy]".center(width), "#{year}".center(width)]
months.each_slice(mpr) do |slice|
slice[0].each_index do |i|
rows.push(slice.map {|a| a[i]}.join " ")
end
end
return rows.join("\n")
end
ARGV.length == 1 or abort "usage: #{$0} year"
# Guess width of terminal.
# 1. Obey environment variable COLUMNS.
# 2. Try to require 'io/console' from Ruby 1.9.3.
# 3. Try to run `tput co`.
# 4. Assume 80 columns.
columns = begin Integer(ENV["COLUMNS"] || "")
rescue
begin require 'io/console'; IO.console.winsize[1]
rescue LoadError
begin Integer(`tput cols`)
rescue
80; end; end; end
puts cal(Integer(ARGV[0]), columns) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #MUMPS | MUMPS | BullCow New bull,cow,guess,guessed,ii,number,pos,x
Set number="",x=1234567890
For ii=1:1:4 Do
. Set pos=$Random($Length(x))+1
. Set number=number_$Extract(x,pos)
. Set $Extract(x,pos)=""
. Quit
Write !,"The computer has selected a number that consists"
Write !,"of four different digits."
Write !!,"As you are guessing the number, ""bulls"" and ""cows"""
Write !,"will be awarded: a ""bull"" for each digit that is"
Write !,"placed in the correct position, and a ""cow"" for each"
Write !,"digit that occurs in the number, but in a different place.",!
Write !,"For a guess, enter 4 digits."
Write !,"Any other input is interpreted as ""I give up"".",!
Set guessed=0 For Do Quit:guessed
. Write !,"Your guess: " Read guess If guess'?4n Set guessed=-1 Quit
. Set (bull,cow)=0,x=guess
. For ii=4:-1:1 If $Extract(x,ii)=$Extract(number,ii) Do
. . Set bull=bull+1,$Extract(x,ii)=""
. . Quit
. For ii=1:1:$Length(x) Set:number[$Extract(x,ii) cow=cow+1
. Write !,"You guessed ",guess,". That earns you "
. If 'bull,'cow Write "neither bulls nor cows..." Quit
. If bull Write bull," bull" Write:bull>1 "s"
. If cow Write:bull " and " Write cow," cow" Write:cow>1 "s"
. Write "."
. If bull=4 Set guessed=1 Write !,"That's a perfect score."
. Quit
If guessed<0 Write !!,"The number was ",number,".",!
Quit
Do BullCow
The computer has selected a number that consists
of four different digits.
As you are guessing the number, "bulls" and "cows"
will be awarded: a "bull" for each digit that is
placed in the correct position, and a "cow" for each
digit that occurs in the number, but in a different place.
For a guess, enter 4 digits.
Any other input is interpreted as "I give up".
Your guess: 1234
You guessed 1234. That earns you 1 cow.
Your guess: 5678
You guessed 5678. That earns you 1 cow.
Your guess: 9815
You guessed 9815. That earns you 1 cow.
Your guess: 9824
You guessed 9824. That earns you 2 cows.
Your guess: 9037
You guessed 9037. That earns you 1 bull and 2 cows.
Your guess: 9048
You guessed 2789. That earns you 1 bull and 2 cows.
Your guess: 2079
You guessed 2079. That earns you 1 bull and 3 cows.
Your guess: 2709
You guessed 2709. That earns you 2 bulls and 2 cows.
Your guess: 0729
You guessed 0729. That earns you 4 cows.
Your guess: 2907
You guessed 2907. That earns you 4 bulls.
That's a perfect score. |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Java | Java | public class Cipher {
public static void main(String[] args) {
String str = "The quick brown fox Jumped over the lazy Dog";
System.out.println( Cipher.encode( str, 12 ));
System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
}
public static String decode(String enc, int offset) {
return encode(enc, 26-offset);
}
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #QBasic | QBasic | FUNCTION Copialo$ (txt$, siNo, final$)
DIM nuevaCadena$
FOR cont = 1 TO siNo
nuevaCadena$ = nuevaCadena$ + txt$
NEXT cont
Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) + final$
END FUNCTION
SUB Saludo
PRINT "Hola mundo!"
END SUB
SUB testCadenas (txt$)
FOR cont = 1 TO LEN(txt$)
PRINT MID$(txt$, cont, 1); "";
NEXT cont
END SUB
SUB testNumeros (a, b, c)
PRINT a, b, c
END SUB
CALL Saludo
PRINT Copialo$("Saludos ", 6, "")
PRINT Copialo$("Saludos ", 3, "!!")
PRINT
CALL testNumeros(1, 2, 3)
CALL testNumeros(1, 2, 0)
PRINT
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'") |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Scheme | Scheme | (define (catalan m)
(let loop ((c 1)(n 0))
(if (not (eqv? n m))
(begin
(display n)(display ": ")(display c)(newline)
(loop (* (/ (* 2 (- (* 2 (+ n 1)) 1)) (+ (+ n 1) 1)) c) (+ n 1) )))))
(catalan 15) |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Rust | Rust | // Assume your binary name is 'calendar'.
// Command line:
// >>$ calendar 2019 150
// First argument: year number.
// Second argument (optional): text area width (in characters).
extern crate chrono;
use std::{env, cmp};
use chrono::{NaiveDate, Datelike};
const MONTH_WIDTH: usize = 22;
fn print_header(months: &[&str]) {
const DAYS_OF_WEEK: &str = "SU MO TU WE TH FR SA ";
println!();
for m in months {
print!("{:^20} ", m);
}
println!("\n{}", DAYS_OF_WEEK.repeat(months.len()));
}
fn get_week_str(days: i32, week_num: i32, start_day_of_week: i32) -> Option<String> {
let start = week_num * 7 - start_day_of_week + 1;
let end = (week_num + 1) * 7 - start_day_of_week;
let mut ret = String::with_capacity(MONTH_WIDTH);
if start > days {
None
} else {
for i in start..(end + 1) {
if i <= 0 || i > days {
ret.push_str(" ");
} else {
if i < 10 {
ret.push_str(" ");
}
ret.push_str(&i.to_string());
}
ret.push_str(" ");
}
ret.push_str(" ");
Some(ret)
}
}
fn main() {
const MONTH_NAMES: [&str; 12] = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
"AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
const DEFAULT_TEXT_WIDTH: usize = 100;
let args: Vec<String> = env::args().collect();
let year: i32 = args[1].parse().expect("The first argument must be a year");
let width: usize = if args.len() > 2 {
cmp::max(MONTH_WIDTH, args[2].parse().expect("The second argument should be text width"))
} else {
DEFAULT_TEXT_WIDTH
};
let months_in_row = width / MONTH_WIDTH;
let month_rows = if MONTH_NAMES.len() % months_in_row == 0 {
MONTH_NAMES.len() / months_in_row
} else {
MONTH_NAMES.len() / months_in_row + 1
};
let start_days_of_week: Vec<i32> =
(1..13).map(|x| NaiveDate::from_ymd(year, x, 1).weekday().num_days_from_sunday() as i32).collect();
let month_days: [i32; 12] = if NaiveDate::from_ymd_opt(year, 2, 29).is_some() {
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
} else {
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
};
println!("{year:^w$}", w=width, year=year.to_string());
for i in 0..month_rows {
let start = i * months_in_row;
let end = cmp::min((i + 1) * months_in_row, MONTH_NAMES.len());
print_header(&MONTH_NAMES[start..end]);
let mut count = 0;
let mut row_num = 0;
while count < months_in_row {
let mut row_str = String::with_capacity(width);
for j in start..end {
match get_week_str(month_days[j], row_num, start_days_of_week[j]) {
None => {
count += 1;
row_str.push_str(&" ".repeat(MONTH_WIDTH));
},
Some(week_str) => row_str.push_str(&week_str)
}
}
if count < months_in_row {
println!("{}", row_str);
}
row_num += 1;
}
}
}
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Nanoquery | Nanoquery | import Nanoquery.Util; random = new(Random)
// a function to verify the user's input
def verify_digits(input)
global size
seen = ""
if len(input) != size
return false
else
for char in input
if not char in "0123456789"
return false
else if char in seen
return false
end
seen += char
end
end
return true
end
size = 4
chosen = ""
while len(chosen) < size
digit = random.getInt(8) + 1
if not str(digit) in chosen
chosen += str(digit)
end
end
println "I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order."
println "You need to input a 4 digit, unique digit number as a guess at what I have chosen."
guesses = 1
won = false
while !won
print "\nNext guess [" + str(guesses) + "]: "
guess = input()
if !verify_digits(guess)
println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
else
if guess = chosen
won = true
else
bulls = 0
cows = 0
for i in range(0, size - 1)
if guess[i] = chosen[i]
bulls += 1
else if guess[i] in chosen
cows += 1
end
end
println format(" %d Bulls\n %d Cows", bulls, cows)
guesses += 1
end
end
end
println "\nCongratulations you guess correctly in " + guesses + " attempts" |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #JavaScript | JavaScript | function caesar (text, shift) {
return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) {
return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);
});
}
// Tests
var text = 'veni, vidi, vici';
for (var i = 0; i<26; i++) {
console.log(i+': '+caesar(text,i));
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Quackery | Quackery | /O> 123 7 /mod
...
Stack: 17 4
/O> 2 pack
...
Stack: [ 17 4 ]
/O> echo cr
...
[ 17 4 ]
Stack empty. |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
local
var bigInteger: n is 0_;
begin
for n range 0_ to 15_ do
writeln((2_ * n) ! n div succ(n));
end for;
end func; |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Scala | Scala | import java.util.{ Calendar, GregorianCalendar }
import language.postfixOps
import collection.mutable.ListBuffer
object CalendarPrint extends App {
val locd = java.util.Locale.getDefault()
val cal = new GregorianCalendar
val monthsMax = cal.getMaximum(Calendar.MONTH)
def JDKweekDaysToISO(dn: Int) = {
val nday = dn - Calendar.MONDAY
if (nday < 0) (dn + Calendar.THURSDAY) else nday
}
def daysInMonth(year: Int, monthMinusOne: Int): Int = {
cal.set(year, monthMinusOne, 1)
cal.getActualMaximum(Calendar.DAY_OF_MONTH)
}
def namesOfMonths() = {
def f1(i: Int): String = {
cal.set(2013, i, 1)
cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locd)
}
(0 to monthsMax) map f1
}
def offsets(year: Int): List[Int] = {
val months = cal.getMaximum(Calendar.MONTH)
def get1stDayOfWeek(i: Int) = {
cal.set(year, i, 1)
cal.get(Calendar.DAY_OF_WEEK)
}
(0 to monthsMax).toList map get1stDayOfWeek map { i => JDKweekDaysToISO(i) }
}
def headerNameOfDays() = {
val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locd) // map days of week
val it = mdow.keySet.iterator
val keySet = new ListBuffer[String]
while (it.hasNext) keySet += it.next
(keySet.map { key => (JDKweekDaysToISO(mdow.get(key)), key.take(2))
}.sortWith(_._1 < _._1) map (_._2)).mkString(" ")
}
def getGregCal(year: Int) = {
{
def dayOfMonth(month: Int) = new Iterator[(Int, Int)] {
cal.set(year, month, 1)
var ldom = 0
def next() = {
val res = (cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH))
ldom = res._2
cal.roll(Calendar.DAY_OF_MONTH, true)
res
}
def hasNext() = (cal.get(Calendar.DAY_OF_MONTH) > ldom)
}
var ret: List[(Int, Int)] = Nil
for (i <- 0 to monthsMax) ret = ret ++ (dayOfMonth(i).toSeq)
(ret, offsets(year))
}
}
def printCalendar(calendar: (List[(Int, Int)], List[Int]),
headerList: List[String] = Nil,
printerWidth: Int = 80) = {
val mw = 20 // month width
val gwf = 2 // gap width fixed
val gwm = 2 // gap width minimum
val fgw = true
val arr = Array.ofDim[String](6, 7)
def limits(printerWidth: Int): (Int, Int, Int, Int, Int) = {
val pw = if (printerWidth < 20) 20 else if (printerWidth > 300) 300 else printerWidth
// months side by side, gaps sum minimum
val (msbs, gsm) = {
val x1 = {
val c = if (pw / mw > 12) 12 else pw / mw
val a = (c - 1)
if (c * mw + a * gwm <= pw) c else a
} match {
case 5 => 4
case a if (a > 6 && a < 12) => 6
case other => other
}
(x1, (x1 - 1) * gwm)
}
def getFGW(msbs: Int, gsm: Int) = { val r = (pw - msbs * mw - gsm) / 2; (r, gwf, r) } // fixed gap width
def getVGW(msbs: Int, gsm: Int) = pw - msbs * mw - gsm match { // variable gap width
case a if (a < 2 * gwm) => (a / 2, gwm, a / 2)
case b => { val x = (b + gsm) / (msbs + 1); (x, x, x) }
}
// left margin, gap width, right margin
val (lm, gw, rm) = if (fgw) getFGW(msbs, gsm) else getVGW(msbs, gsm)
(pw, msbs, lm, gw, rm)
} // def limits(
val (pw, msbs, lm, gw, rm) = limits(printerWidth)
val monthsList = (0 to monthsMax).map { m => calendar._1.filter { _._1 == m } }
val nom = namesOfMonths()
val hnod = headerNameOfDays
def fsplit(list: List[(Int, Int)]): List[String] = {
def fap(p: Int) = (p / 7, p % 7)
for (i <- 0 until 6) for (j <- 0 until 7) arr(i)(j) = " "
for (i <- 0 until list.size)
arr(fap(i + calendar._2(list(i)._1))._1)(fap(i + calendar._2(list(i)._1))._2) =
f"${(list(i)._2)}%2d"
arr.toList.map(_.foldRight("")(_ + " " + _))
}
val monthsRows = monthsList.map(fsplit)
def center(s: String, l: Int): String = {
(if (s.size >= l) s
else " " * ((l - s.size) / 2) + s + " " * ((l - s.size) / 2) + " ").substring(0, l)
}
val maxMonths = monthsMax + 1
val rowblocks = (1 to maxMonths / msbs).map { i =>
(0 to 5).map { j =>
val lb = new ListBuffer[String]
val k = (i - 1) * msbs
(k to k + msbs - 1).map { l => lb += monthsRows(l)(j) }
lb
}
}
val mheaders = (1 to maxMonths / msbs).
map { i => (0 to msbs - 1).map { j => center(nom(j + (i - 1) * msbs), 20) } }
val dowheaders = (1 to maxMonths / msbs).
map { i => (0 to msbs - 1).map { j => center(hnod, 20) } }
headerList.foreach(xs => println(center(xs + '\n', pw)))
(1 to 12 / msbs).foreach { i =>
println(" " * lm + mheaders(i - 1).foldRight("")(_ + " " * gw + _))
println(" " * lm + dowheaders(i - 1).foldRight("")(_ + " " * gw + _))
rowblocks(i - 1).foreach { xs => println(" " * lm + xs.foldRight("")(_ + " " * (gw - 1) + _)) }
println
}
} // def printCal(
printCalendar(getGregCal(1969), List("[Snoopy Picture]", "1969"))
printCalendar(getGregCal(1582), List("[Snoopy Picture]", "1582"), printerWidth = 132)
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Nim | Nim | import random, strutils, strformat, sequtils
randomize()
const
Digits = "123456789"
DigitSet = {Digits[0]..Digits[^1]}
Size = 4
proc sample(s: string; n: Positive): string =
## Return a random sample of "n" characters extracted from string "s".
var s = s
s.shuffle()
result = s[0..<n]
proc plural(n: int): string =
if n > 1: "s" else: ""
let chosen = Digits.sample(Size)
echo &"I have chosen a number from {Size} unique digits from 1 to 9 arranged in a random order."
echo &"You need to input a {Size} digit, unique digit number as a guess at what I have chosen."
var guesses = 0
while true:
inc guesses
var guess = ""
while true:
stdout.write(&"\nNext guess {guesses}: ")
guess = stdin.readLine().strip()
if guess.len == Size and allCharsInSet(guess, DigitSet) and guess.deduplicate.len == Size:
break
echo &"Problem, try again. You need to enter {Size} unique digits from 1 to 9."
if guess == chosen:
echo &"\nCongratulations! You guessed correctly in {guesses} attempts."
break
var bulls, cows = 0
for i in 0..<Size:
if guess[i] == chosen[i]: inc bulls
elif guess[i] in chosen: inc cows
echo &" {bulls} Bull{plural(bulls)}\n {cows} Cow{plural(cows)}" |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #jq | jq | def encrypt(key):
. as $s
| explode as $xs
| (key % 26) as $offset
| if $offset == 0 then .
else reduce range(0; length) as $i ( {chars: []};
$xs[$i] as $c
| .d = $c
| if ($c >= 65 and $c <= 90) # 'A' to 'Z'
then .d = $c + $offset
| if (.d > 90) then .d += -26 else . end
else if ($c >= 97 and $c <= 122) # 'a' to 'z'
then .d = $c + $offset
| if (.d > 122)
then .d += -26
else .
end
else .
end
end
| .chars[$i] = .d )
| .chars | implode
end ;
def decrypt(key): encrypt(26 - key);
"Bright vixens jump; dozy fowl quack."
| .,
(encrypt(8)
| ., decrypt(8) )
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #R | R | ### Calling a function that requires no arguments
no_args <- function() NULL
no_args()
### Calling a function with a fixed number of arguments
fixed_args <- function(x, y) print(paste("x=", x, ", y=", y, sep=""))
fixed_args(1, 2) # x=1, y=2
fixed_args(y=2, x=1) # y=1, x=2
### Calling a function with optional arguments
opt_args <- function(x=1) x
opt_args() # x=1
opt_args(3.141) # x=3.141
### Calling a function with a variable number of arguments
var_args <- function(...) print(list(...))
var_args(1, 2, 3)
var_args(1, c(2,3))
var_args()
### Calling a function with named arguments
fixed_args(y=2, x=1) # x=1, y=2
### Using a function in statement context
if (TRUE) no_args()
### Using a function in first-class context within an expression
print(no_args)
### Obtaining the return value of a function
return_something <- function() 1
x <- return_something()
x
### Distinguishing built-in functions and user-defined functions
# Not easily possible. See
# http://cran.r-project.org/doc/manuals/R-ints.html#g_t_002eInternal-vs-_002ePrimitive
# for details.
### Distinguishing subroutines and functions
# No such distinction.
### Stating whether arguments are passed by value or by reference
# Pass by value.
### Is partial application possible and how
# Yes, see http://rosettacode.org/wiki/Partial_function_application#R |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Sidef | Sidef | func f(i) { i==0 ? 1 : (i * f(i-1)) }
func c(n) { f(2*n) / f(n) / f(n+1) } |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
const func string: center (in string: stri, in integer: length) is
return ("" lpad (length - length(stri)) div 2 <& stri) rpad length;
const proc: printCalendar (in integer: year, in integer: cols) is func
local
var time: date is time.value;
var integer: dayOfWeek is 0;
const array string: monthNames is [] ("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
var array array string: monthTable is 12 times 9 times "";
var string: str is "";
var integer: month is 0;
var integer: position is 0;
var integer: row is 0;
var integer: column is 0;
var integer: line is 0;
begin
for month range 1 to 12 do
monthTable[month][1] := " " & center(monthNames[month], 20);
monthTable[month][2] := " Mo Tu We Th Fr Sa Su";
date := date(year, month, 1);
dayOfWeek := dayOfWeek(date);
for position range 1 to 43 do
if position >= dayOfWeek and position - dayOfWeek < daysInMonth(date.year, date.month) then
str := succ(position - dayOfWeek) lpad 3;
else
str := "" lpad 3;
end if;
monthTable[month][3 + pred(position) div 7] &:= str;
end for;
end for;
writeln(center("[Snoopy Picture]", cols * 24 + 4));
writeln(center(str(year),cols * 24 + 4));
writeln;
for row range 1 to succ(11 div cols) do
for line range 1 to 9 do
for column range 1 to cols do
if pred(row) * cols + column <= 12 then
write(" " & monthTable[pred(row) * cols + column][line]);
end if;
end for;
writeln;
end for;
end for;
end func;
const proc: main is func
begin
printCalendar(1969, 3);
end func; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #OCaml | OCaml | let rec input () =
let s = read_line () in
try
if String.length s <> 4 then raise Exit;
String.iter (function
| '1'..'9' -> ()
| _ -> raise Exit
) s;
let t = [ s.[0]; s.[1]; s.[2]; s.[3] ] in
let _ = List.fold_left (* reject entry with duplication *)
(fun ac b -> if List.mem b ac then raise Exit; (b::ac))
[] t in
List.map (fun c -> int_of_string (String.make 1 c)) t
with Exit ->
prerr_endline "That is an invalid entry. Please try again.";
input ()
;;
let print_score g t =
let bull = ref 0 in
List.iter2 (fun x y ->
if x = y then incr bull
) g t;
let cow = ref 0 in
List.iter (fun x ->
if List.mem x t then incr cow
) g;
cow := !cow - !bull;
Printf.printf "%d bulls, %d cows\n%!" !bull !cow
;;
let () =
Random.self_init ();
let rec mkgoal acc = function 4 -> acc
| i ->
let n = succ(Random.int 9) in
if List.mem n acc
then mkgoal acc i
else mkgoal (n::acc) (succ i)
in
let g = mkgoal [] 0 in
let found = ref false in
while not !found do
let t = input () in
if t = g
then found := true
else print_score g t
done;
print_endline "Congratulations you guessed correctly";
;; |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Jsish | Jsish | /* Caesar cipher, in Jsish */
"use strict";
function caesarCipher(input:string, key:number):string {
return input.replace(/([a-z])/g,
function(mat, p1, ofs, str) {
return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 97) % 26 + 97);
}).replace(/([A-Z])/g,
function(mat, p1, ofs, str) {
return Util.fromCharCode((p1.charCodeAt(0) + key + 26 - 65) % 26 + 65);
});
}
provide('caesarCipher', 1);
if (Interp.conf('unitTest')) {
var str = 'The five boxing wizards jump quickly';
; str;
; 'Enciphered:';
; caesarCipher(str, 3);
; 'Enciphered then deciphered';
; caesarCipher(caesarCipher(str, 3), -3);
}
/*
=!EXPECTSTART!=
str ==> The five boxing wizards jump quickly
'Enciphered:'
caesarCipher(str, 3) ==> Wkh ilyh eralqj zlcdugv mxps txlfnob
'Enciphered then deciphered'
caesarCipher(caesarCipher(str, 3), -3) ==> The five boxing wizards jump quickly
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Racket | Racket |
#lang racket
;; Calling a function that requires no arguments
(foo)
;; Calling a function with a fixed number of arguments
(foo 1 2 3)
;; Calling a function with optional arguments
;; Calling a function with a variable number of arguments
(foo 1 2 3) ; same in both cases
;; Calling a function with named arguments
(foo 1 2 #:x 3) ; using #:keywords for the names
;; Using a function in statement context
;; Using a function in first-class context within an expression
;; Obtaining the return value of a function
;; -> Makes no sense for Racket, as well as most other functional PLs
;; Distinguishing built-in functions and user-defined functions
(primitive? foo)
;; but this is mostly useless, since most of Racket is implemented in
;; itself
;; Distinguishing subroutines and functions
;; -> No difference, though `!' is an idiomatic suffix for names of
;; side-effect functions, and they usually return (void)
;; Stating whether arguments are passed by value or by reference
;; -> Always by value, but it's possible to implement languages with
;; other argument passing styles, including passing arguments by
;; reference (eg, there is "#lang algol60")
;; Is partial application possible and how
(curry foo 1 2) ; later apply this on 3
(λ(x) (foo 1 2 x)) ; a direct way of doing the same
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Raku | Raku | foo # as list operator
foo() # as function
foo.() # as function, explicit postfix form
$ref() # as object invocation
$ref.() # as object invocation, explicit postfix
&foo() # as object invocation
&foo.() # as object invocation, explicit postfix
::($name)() # as symbolic ref |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #smart_BASIC | smart BASIC | PRINT "Recursive:"!PRINT
FOR n = 0 TO 15
PRINT n,"#######":catrec(n)
NEXT n
PRINT!PRINT
PRINT "Non-recursive:"!PRINT
FOR n = 0 TO 15
PRINT n,"#######":catnonrec(n)
NEXT n
END
DEF catrec(x)
IF x = 0 THEN
temp = 1
ELSE
n = x
temp = ((2*((2*n)-1))/(n+1))*catrec(n-1)
END IF
catrec = temp
END DEF
DEF catnonrec(x)
temp = 1
FOR n = 1 TO x
temp = (2*((2*n)-1))/(n+1)*temp
NEXT n
catnonrec = temp
END DEF |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Sidef | Sidef | require('DateTime')
define months_per_col = 3
define week_day_names = <Mo Tu We Th Fr Sa Su>
define month_names = <Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec>
func fmt_month (year, month) {
var str = sprintf("%-20s\n", month_names[month-1])
str += week_day_names.join(' ')+"\n"
var dt = %s<DateTime>
var date = dt.new(year => year, month => month)
var week_day = date.day_of_week
str += (week_day-1 `of` " " -> join(" "))
var last_day = dt.last_day_of_month(year => year, month => month).day
for day (date.day .. last_day) {
date = dt.new(year => year, month => month, day => day)
str += " " if (week_day ~~ (2..7))
if (week_day == 8) {
str += "\n"
week_day = 1
}
str += sprintf("%2d", day)
++week_day
}
str += " " if (week_day < 8)
str += (8-week_day `of` " " -> join(" "))
str += "\n"
}
func fmt_year (year) {
var month_strs = 12.of {|i| fmt_month(year, i+1).lines }
var str = (' '*30 + year + "\n")
for month (0..11 `by` months_per_col) {
while (month_strs[month]) {
for i (1..months_per_col) {
month_strs[month + i - 1] || next
str += month_strs[month + i - 1].shift
str += ' '*3
}
str += "\n"
}
str += "\n"
}
return str
}
print fmt_year(ARGV ? Number(ARGV[0]) : 1969) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Oforth | Oforth | : bullsAndCows
| numbers guess digits bulls cows |
ListBuffer new ->numbers
while(numbers size 4 <>) [ 9 rand dup numbers include ifFalse: [ numbers add ] else: [ drop ] ]
while(true) [
"Enter a number of 4 different digits between 1 and 9 : " print
System.Console askln ->digits
digits asInteger isNull digits size 4 <> or ifTrue: [ "Number of four digits needed" println continue ]
digits map(#asDigit) ->guess
guess numbers zipWith(#==) occurrences(true) ->bulls
bulls 4 == ifTrue: [ "You won !" println return ]
guess filter(#[numbers include]) size bulls - ->cows
System.Out "Bulls = " << bulls << ", cows = " << cows << cr
] ; |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Julia | Julia |
# Caeser cipher
# Julia 1.5.4
# author: manuelcaeiro | https://github.com/manuelcaeiro
function csrcipher(text, key)
ciphtext = ""
for l in text
numl = Int(l)
ciphnuml = numl + key
if numl in 65:90
if ciphnuml > 90
rotciphnuml = ciphnuml - 26
ciphtext = ciphtext * Char(rotciphnuml)
else
ciphtext = ciphtext * Char(ciphnuml)
end
elseif numl in 97:122
if ciphnuml > 122
rotciphnuml = ciphnuml - 26
ciphtext = ciphtext * Char(rotciphnuml)
else
ciphtext = ciphtext * Char(ciphnuml)
end
else
ciphtext = ciphtext * Char(numl)
end
end
return ciphtext
end
text = "Magic Encryption"; key = 13
csrcipher(text, key)
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #REXX | REXX | /*REXX pgms demonstrates various methods/approaches of invoking/calling a REXX function.*/
/*╔════════════════════════════════════════════════════════════════════╗
║ Calling a function that REQUIRES no arguments. ║
║ ║
║ In the REXX language, there is no way to require the caller to not ║
║ pass arguments, but the programmer can check if any arguments were ║
║ (or weren't) passed. ║
╚════════════════════════════════════════════════════════════════════╝*/
yr= yearFunc() /*the function name is caseless if it isn't */
/*enclosed in quotes (') or apostrophes (").*/
say 'year=' yr
exit /*stick a fork in it, we're all done. */
yearFunc: procedure /*function ARG returns the # of args.*/
errmsg= '***error***' /*an error message eyecatcher string. */
if arg() \== 0 then say errmsg "the YEARFUNC function won't accept arguments."
return left( date('Sorted'), 3) |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Standard_ML | Standard ML | (*
* val catalan : int -> int
* Returns the nth Catalan number.
*)
fun catalan 0 = 1
| catalan n = ((4 * n - 2) * catalan(n - 1)) div (n + 1);
(*
* val print_catalans : int -> unit
* Prints out Catalan numbers 0 through 15.
*)
fun print_catalans(n) =
if n > 15 then ()
else (print (Int.toString(catalan n) ^ "\n"); print_catalans(n + 1)); print_catalans(0);
(*
* 1
* 1
* 2
* 5
* 14
* 42
* 132
* 429
* 1430
* 4862
* 16796
* 58786
* 208012
* 742900
* 2674440
* 9694845
*) |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Simula | Simula | BEGIN
INTEGER WIDTH, YEAR;
INTEGER COLS, LEAD, GAP;
TEXT ARRAY WDAYS(0:6);
CLASS MONTH(MNAME); TEXT MNAME;
BEGIN INTEGER DAYS, START_WDAY, AT_POS;
END MONTH;
REF(MONTH) ARRAY MONTHS(0:11);
WIDTH := 80; YEAR := 1969;
BEGIN
TEXT T;
INTEGER I, M;
FOR T :- "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" DO BEGIN
WDAYS(I) :- T; I := I+1;
END;
I := 0;
FOR T :- "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" DO BEGIN
MONTHS(I) :- NEW MONTH(T); I := I+1;
END;
I := 0;
FOR M := 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 DO BEGIN
MONTHS(I).DAYS := M; I := I+1;
END;
END;
BEGIN
PROCEDURE SPACE(N); INTEGER N;
BEGIN
WHILE N > 0 DO BEGIN
OUTCHAR(' '); N := N-1;
END;
END SPACE;
PROCEDURE INIT_MONTHS;
BEGIN
INTEGER I;
IF MOD(YEAR,4) = 0 AND MOD(YEAR,100) <> 0 OR MOD(YEAR,400) = 0 THEN
MONTHS(1).DAYS := 29;
YEAR := YEAR-1;
MONTHS(0).START_WDAY
:= MOD(YEAR * 365 + YEAR//4 - YEAR//100 + YEAR//400 + 1, 7);
FOR I := 1 STEP 1 UNTIL 12-1 DO
MONTHS(I).START_WDAY :=
MOD(MONTHS(I-1).START_WDAY + MONTHS(I-1).DAYS, 7);
COLS := (WIDTH + 2) // 22;
WHILE MOD(12,COLS) <> 0 DO
COLS := COLS-1;
GAP := IF COLS - 1 <> 0 THEN (WIDTH - 20 * COLS) // (COLS - 1) ELSE 0;
IF GAP > 4 THEN
GAP := 4;
LEAD := (WIDTH - (20 + GAP) * COLS + GAP + 1) // 2;
YEAR := YEAR+1;
END INIT_MONTHS;
PROCEDURE PRINT_ROW(ROW); INTEGER ROW;
BEGIN
INTEGER C, I, FROM, UP_TO;
INTEGER PROCEDURE PREINCREMENT(I); NAME I; INTEGER I;
BEGIN I := I+1; PREINCREMENT := I;
END PREINCREMENT;
INTEGER PROCEDURE POSTINCREMENT(I); NAME I; INTEGER I;
BEGIN POSTINCREMENT := I; I := I+1;
END POSTINCREMENT;
FROM := ROW * COLS;
UP_TO := FROM + COLS;
SPACE(LEAD);
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
I := MONTHS(C).MNAME.LENGTH;
SPACE((20 - I)//2);
OUTTEXT(MONTHS(C).MNAME);
SPACE(20 - I - (20 - I)//2 + (IF C = UP_TO - 1 THEN 0 ELSE GAP));
END;
OUTIMAGE;
SPACE(LEAD);
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
FOR I := 0 STEP 1 UNTIL 7-1 DO BEGIN
OUTTEXT(WDAYS(I)); OUTTEXT(IF I = 6 THEN "" ELSE " ");
END;
IF C < UP_TO - 1 THEN
SPACE(GAP)
ELSE
OUTIMAGE;
END;
WHILE TRUE DO BEGIN
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO
IF MONTHS(C).AT_POS < MONTHS(C).DAYS THEN
GO TO IBREAK;
IBREAK:
IF C = UP_TO THEN
GO TO OBREAK;
SPACE(LEAD);
FOR C := FROM STEP 1 UNTIL UP_TO-1 DO BEGIN
FOR I := 0 STEP 1 UNTIL MONTHS(C).START_WDAY-1 DO
SPACE(3);
WHILE POSTINCREMENT(I) < 7 AND MONTHS(C).AT_POS < MONTHS(C).DAYS DO BEGIN
OUTINT(PREINCREMENT(MONTHS(C).AT_POS),2);
IF I < 7 OR C < UP_TO - 1 THEN
SPACE(1);
END;
WHILE POSTINCREMENT(I) <= 7 AND C < UP_TO-1 DO
SPACE(3);
IF C < UP_TO - 1 THEN
SPACE(GAP - 1);
MONTHS(C).START_WDAY := 0;
END;
OUTIMAGE;
END;
OBREAK:
OUTIMAGE;
END PRINT_ROW;
PROCEDURE PRINT_YEAR;
BEGIN
INTEGER ROW;
TEXT BUF;
INTEGER STRLEN;
BUF :- BLANKS(32); BUF.PUTINT(YEAR); BUF.SETPOS(1);
WHILE BUF.MORE AND THEN BUF.GETCHAR = ' ' DO
STRLEN := STRLEN+1;
BUF :- BUF.SUB(STRLEN+1, 32-STRLEN);
SPACE((WIDTH - BUF.LENGTH) // 2);
OUTTEXT(BUF); OUTIMAGE; OUTIMAGE;
WHILE ROW * COLS < 12 DO BEGIN
PRINT_ROW(ROW);
ROW := ROW+1;
END;
END PRINT_YEAR;
INIT_MONTHS;
PRINT_YEAR;
END;
END; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #ooRexx | ooRexx | declare
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
proc {Loop}
Guess = {EnterGuess}
in
{System.showInfo
{Bulls Guess Solution}#" bulls and "#
{Cows Guess Solution}#" cows"}
if Guess \= Solution then {Loop} end
end
in
{Loop}
{System.showInfo "You have won!"}
end
fun {Bulls Xs Sol}
{Length {Filter {List.zip Xs Sol Value.'=='} Id}}
end
fun {Cows Xs Sol}
{Length {Intersection Xs Sol}}
end
local
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
in
fun {EnterGuess}
try
{System.printInfo "Enter your guess (e.g. \"1234\"): "}
S = {StdIn getS($)}
in
%% verify
{Length S} = 4
{All S Char.isDigit} = true
{FD.distinct S} %% assert there is no duplicate digit
%% convert from digits to numbers
{Map S fun {$ D} D-&0 end}
catch _ then
{EnterGuess}
end
end
end
fun {PickNUnique N Xs}
{FoldL {MakeList N}
fun {$ Z _}
{Pick {Diff Xs Z}}|Z
end
nil}
end
fun {Pick Xs}
{Nth Xs {OS.rand} mod {Length Xs} + 1}
end
fun {Diff Xs Ys}
{FoldL Ys List.subtract Xs}
end
fun {Intersection Xs Ys}
{Filter Xs fun {$ X} {Member X Ys} end}
end
fun {Id X} X end
in
{Main} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #K | K |
s:"there is a tide in the affairs of men"
caesar:{ :[" "=x; x; {x!_ci 97+!26}[y]@_ic[x]-97]}'
caesar[s;1]
"uifsf jt b ujef jo uif bggbjst pg nfo"
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Ring | Ring |
hello()
func hello
see "Hello from function" + nl
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Ruby | Ruby | fn main() {
// Rust has a lot of neat things you can do with functions: let's go over the basics first
fn no_args() {}
// Run function with no arguments
no_args();
// Calling a function with fixed number of arguments.
// adds_one takes a 32-bit signed integer and returns a 32-bit signed integer
fn adds_one(num: i32) -> i32 {
// the final expression is used as the return value, though `return` may be used for early returns
num + 1
}
adds_one(1);
// Optional arguments
// The language itself does not support optional arguments, however, you can take advantage of
// Rust's algebraic types for this purpose
fn prints_argument(maybe: Option<i32>) {
match maybe {
Some(num) => println!("{}", num),
None => println!("No value given"),
};
}
prints_argument(Some(3));
prints_argument(None);
// You could make this a bit more ergonomic by using Rust's Into trait
fn prints_argument_into<I>(maybe: I)
where I: Into<Option<i32>>
{
match maybe.into() {
Some(num) => println!("{}", num),
None => println!("No value given"),
};
}
prints_argument_into(3);
prints_argument_into(None);
// Rust does not support functions with variable numbers of arguments. Macros fill this niche
// (println! as used above is a macro for example)
// Rust does not support named arguments
// We used the no_args function above in a no-statement context
// Using a function in an expression context
adds_one(1) + adds_one(5); // evaluates to eight
// Obtain the return value of a function.
let two = adds_one(1);
// In Rust there are no real built-in functions (save compiler intrinsics but these must be
// manually imported)
// In rust there are no such thing as subroutines
// In Rust, there are three ways to pass an object to a function each of which have very important
// distinctions when it comes to Rust's ownership model and move semantics. We may pass by
// value, by immutable reference, or mutable reference.
let mut v = vec![1, 2, 3, 4, 5, 6];
// By mutable reference
fn add_one_to_first_element(vector: &mut Vec<i32>) {
vector[0] += 1;
}
add_one_to_first_element(&mut v);
// By immutable reference
fn print_first_element(vector: &Vec<i32>) {
println!("{}", vector[0]);
}
print_first_element(&v);
// By value
fn consume_vector(vector: Vec<i32>) {
// We can do whatever we want to vector here
}
consume_vector(v);
// Due to Rust's move semantics, v is now inaccessible because it was moved into consume_vector
// and was then dropped when it went out of scope
// Partial application is not possible in rust without wrapping the function in another
// function/closure e.g.:
fn average(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
let average_with_four = |y| average(4.0, y);
average_with_four(2.0);
} |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Stata | Stata | clear
set obs 15
gen catalan=1 in 1
replace catalan=catalan[_n-1]*2*(2*_n-3)/_n in 2/l
list, noobs noh |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Smalltalk | Smalltalk | CalendarPrinter printOnTranscriptForYearNumber: 1969 |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Oz | Oz | declare
proc {Main}
Solution = {PickNUnique 4 {List.number 1 9 1}}
proc {Loop}
Guess = {EnterGuess}
in
{System.showInfo
{Bulls Guess Solution}#" bulls and "#
{Cows Guess Solution}#" cows"}
if Guess \= Solution then {Loop} end
end
in
{Loop}
{System.showInfo "You have won!"}
end
fun {Bulls Xs Sol}
{Length {Filter {List.zip Xs Sol Value.'=='} Id}}
end
fun {Cows Xs Sol}
{Length {Intersection Xs Sol}}
end
local
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
in
fun {EnterGuess}
try
{System.printInfo "Enter your guess (e.g. \"1234\"): "}
S = {StdIn getS($)}
in
%% verify
{Length S} = 4
{All S Char.isDigit} = true
{FD.distinct S} %% assert there is no duplicate digit
%% convert from digits to numbers
{Map S fun {$ D} D-&0 end}
catch _ then
{EnterGuess}
end
end
end
fun {PickNUnique N Xs}
{FoldL {MakeList N}
fun {$ Z _}
{Pick {Diff Xs Z}}|Z
end
nil}
end
fun {Pick Xs}
{Nth Xs {OS.rand} mod {Length Xs} + 1}
end
fun {Diff Xs Ys}
{FoldL Ys List.subtract Xs}
end
fun {Intersection Xs Ys}
{Filter Xs fun {$ X} {Member X Ys} end}
end
fun {Id X} X end
in
{Main} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Kotlin | Kotlin | // version 1.0.5-2
object Caesar {
fun encrypt(s: String, key: Int): String {
val offset = key % 26
if (offset == 0) return s
var d: Char
val chars = CharArray(s.length)
for ((index, c) in s.withIndex()) {
if (c in 'A'..'Z') {
d = c + offset
if (d > 'Z') d -= 26
}
else if (c in 'a'..'z') {
d = c + offset
if (d > 'z') d -= 26
}
else
d = c
chars[index] = d
}
return chars.joinToString("")
}
fun decrypt(s: String, key: Int): String {
return encrypt(s, 26 - key)
}
}
fun main(args: Array<String>) {
val encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
println(encoded)
val decoded = Caesar.decrypt(encoded, 8)
println(decoded)
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Rust | Rust | fn main() {
// Rust has a lot of neat things you can do with functions: let's go over the basics first
fn no_args() {}
// Run function with no arguments
no_args();
// Calling a function with fixed number of arguments.
// adds_one takes a 32-bit signed integer and returns a 32-bit signed integer
fn adds_one(num: i32) -> i32 {
// the final expression is used as the return value, though `return` may be used for early returns
num + 1
}
adds_one(1);
// Optional arguments
// The language itself does not support optional arguments, however, you can take advantage of
// Rust's algebraic types for this purpose
fn prints_argument(maybe: Option<i32>) {
match maybe {
Some(num) => println!("{}", num),
None => println!("No value given"),
};
}
prints_argument(Some(3));
prints_argument(None);
// You could make this a bit more ergonomic by using Rust's Into trait
fn prints_argument_into<I>(maybe: I)
where I: Into<Option<i32>>
{
match maybe.into() {
Some(num) => println!("{}", num),
None => println!("No value given"),
};
}
prints_argument_into(3);
prints_argument_into(None);
// Rust does not support functions with variable numbers of arguments. Macros fill this niche
// (println! as used above is a macro for example)
// Rust does not support named arguments
// We used the no_args function above in a no-statement context
// Using a function in an expression context
adds_one(1) + adds_one(5); // evaluates to eight
// Obtain the return value of a function.
let two = adds_one(1);
// In Rust there are no real built-in functions (save compiler intrinsics but these must be
// manually imported)
// In rust there are no such thing as subroutines
// In Rust, there are three ways to pass an object to a function each of which have very important
// distinctions when it comes to Rust's ownership model and move semantics. We may pass by
// value, by immutable reference, or mutable reference.
let mut v = vec![1, 2, 3, 4, 5, 6];
// By mutable reference
fn add_one_to_first_element(vector: &mut Vec<i32>) {
vector[0] += 1;
}
add_one_to_first_element(&mut v);
// By immutable reference
fn print_first_element(vector: &Vec<i32>) {
println!("{}", vector[0]);
}
print_first_element(&v);
// By value
fn consume_vector(vector: Vec<i32>) {
// We can do whatever we want to vector here
}
consume_vector(v);
// Due to Rust's move semantics, v is now inaccessible because it was moved into consume_vector
// and was then dropped when it went out of scope
// Partial application is not possible in rust without wrapping the function in another
// function/closure e.g.:
fn average(x: f64, y: f64) -> f64 {
(x + y) / 2.0
}
let average_with_four = |y| average(4.0, y);
average_with_four(2.0);
} |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Scala | Scala | def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods
def myFunction0() = ???
myFunction0() // function invoked with empty parameter list
myFunction0 // function invoked with empty parameter list omitted
def myFunction = ???
myFunction // function invoked with no arguments or empty arg list
/* myFunction() */ // error: does not take parameters
def myFunction1(x: String) = ???
myFunction1("foobar") // function invoked with single argument
myFunction1 { "foobar" } // function invoked with single argument provided by a block
// (a block of code within {}'s' evaluates to the result of its last expression)
def myFunction2(first: Int, second: String) = ???
val b = "foobar"
myFunction2(6, b) // function with two arguments
def multipleArgLists(first: Int)(second: Int, third: String) = ???
multipleArgLists(42)(17, "foobar") // function with three arguments in two argument lists
def myOptionalParam(required: Int, optional: Int = 42) = ???
myOptionalParam(1) // function with optional param
myOptionalParam(1, 2) // function with optional param provided
def allParamsOptional(firstOpt: Int = 42, secondOpt: String = "foobar") = ???
allParamsOptional() // function with all optional args
/* allParamsOptional */ // error: missing arguments for method allParamsOptional;
// follow with `_' if you want to treat it as a partially applied function
def sum[Int](values: Int*) = values.foldLeft(0)((a, b) => a + b)
sum(1, 2, 3) // function accepting variable arguments as literal
val values = List(1, 2, 3)
sum(values: _*) // function acception variable arguments from collection
sum() // function accepting empty variable arguments
def mult(firstValue: Int, otherValues: Int*) = otherValues.foldLeft(firstValue)((a, b) => a * b)
mult(1, 2, 3) // function with non-empty variable arguments
myOptionalParam(required = 1) // function called with named arguments (all functions have named arguments)
myFunction2(second = "foo", first = 1) // function with re-ordered named arguments
mult(firstValue = 1, otherValues = 2, 3) // function with named variable argument as literal
val otherValues = Seq(2, 3)
mult(1, otherValues = otherValues: _*) // function with named variable argument from collection
val result = myFunction0() // function called in an expression context
myFunction0() // function called in statement context
/* myOptionalParam(optional = 1, 2) */ // error: positional after named argument.
def transform[In, Out](initial: In)(transformation: In => Out) = transformation(initial)
val result = transform(42)(x => x * x) // function in first-class context within an expression
def divide(top: Double, bottom: Double) = top / bottom
val div = (divide _) // partial application -- defer application of entire arg list
val halve = divide(_: Double, 2) // partial application -- defer application of some arguments
class Foo(var value: Int)
def incFoo(foo: Foo) = foo.value += 1 // function showing AnyRef's are passed by reference
/* def incInt(i: Int) = i += 1 */ // error: += is not a member of Int
// (All arguments are passed by reference, but reassignment
// or setter must be defined on a type or a field
// (respectively) in order to modify its value.)
// No distinction between built-in functions and user-defined functions
// No distinction between subroutines and functions |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Swift | Swift | func catalan(_ n: Int) -> Int {
switch n {
case 0:
return 1
case _:
return catalan(n - 1) * 2 * (2 * n - 1) / (n + 1)
}
}
for i in 1..<16 {
print("catalan(\(i)) => \(catalan(i))")
}
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #SPL | SPL | year = 1969
#.output(#.str(year,">68<"))
> row, 0..3
> col, 1..3
cal[col] = mcal(row*3+col,year)
size = #.size(cal[col],1)
<
> i, 1..8
str = ""
> col, 1..3
? col>1, str += " "
line = ""
? #.size(cal[col],1)!<i, line = cal[col][i]
str += #.str(line,"<20<")
<
#.output(str)
<
<
mcal(m,y)=
months = ["January","February","March","April","May","June","July","August","September","October","November","December"]
days = [31,28,31,30,31,30,31,31,30,31,30,31]
? y%4=0, days[2] = 29
lines = #.array(0)
lines[1] = #.str(months[m],">20<")
lines[2] = "Mo Tu We Th Fr Sa Su"
n = 3
> i, 1..#.weekday(1,m,y)-1
lines[n] += " "
<
> d, 1..days[m]
wd = #.weekday(d,m,y)
lines[n] += #.str(d,">2>")
? wd<7, lines[n] += " "
? wd=7, n += 1
<
<= lines
. |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #PARI.2FGP | PARI/GP | bc()={
my(u,v,bulls,cows);
while(#vecsort(v=vector(4,i,random(9)+1),,8)<4,);
while(bulls<4,
u=input();
if(type(u)!="t_VEC"|#u!=4,next);
bulls=sum(i=1,4,u[i]==v[i]);
cows=sum(i=1,4,sum(j=1,4,i!=j&v[i]==u[j]));
print("You have "bulls" bulls and "cows" cows")
)
}; |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #LabVIEW | LabVIEW |
{def caesar
{def caesar.alphabet {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}}
{def caesar.delta
{lambda {:s :i :a}
{A.get {% {+ {A.in? {A.get :i :a} {caesar.alphabet}} 26 :s} 26}
{caesar.alphabet}}}}
{def caesar.loop
{lambda {:s :a :b :n :i}
{if {> :i :n}
then :b
else {caesar.r :s
:a
{A.set! :i {caesar.delta :s :i :a} :b}
:n
{+ :i 1}} }}}
{lambda {:shift :txt}
{let { {:s :shift}
{:t {S.replace [^A-Z] by in :txt}} }
{A.join {caesar.loop :s
{A.split :t}
{A.new}
{- {W.length :t} 1}
0 }}}}}
-> caesar
{def text VENI, VIDI, VICI}
-> text
{S.map {lambda {:i} {br}:i: {caesar :i {text}}}
{S.serie 0 26}}
->
0: VENIVIDIVICI
1: WFOJWJEJWJDJ
2: XGPKXKFKXKEK
3: YHQLYLGLYLFL
...
23: SBKFSFAFSFZF
24: TCLGTGBGTGAG
25: UDMHUHCHUHBH
26: VENIVIDIVICI
As a shorter alternative:
{def CAESAR
{def CAESAR.rot
{lambda {:shift :txt :alpha :i}
{A.get {% {+ {A.in? {A.get :i :txt} :alpha} 26 :shift} 26}
:alpha}}}
{def CAESAR.loop
{lambda {:shift :txt :alpha}
{S.map {CAESAR.rot :shift :txt :alpha}
{S.serie 0 {- {A.length :txt} 1}}} }}
{lambda {:shift :txt}
{S.replace \s by in
{CAESAR.loop :shift
{A.split {S.replace \s by in :txt}}
{A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}} }}}
-> CAESAR
{CAESAR 1 VENI VIDI VICI}
-> WFOJWJEJWJDJ
{CAESAR 25 WFOJWJEJWJDJ}
-> VENIVIDIVICI
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Seed7 | Seed7 | put zeroArgsFn()
// Function calls can also be made using the following syntax:
put the zeroArgsFn
function zeroArgsFn
put "This function was run with zero arguments."
return "Return value from zero argument function"
end zeroArgsFn |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #SenseTalk | SenseTalk | put zeroArgsFn()
// Function calls can also be made using the following syntax:
put the zeroArgsFn
function zeroArgsFn
put "This function was run with zero arguments."
return "Return value from zero argument function"
end zeroArgsFn |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #Tcl | Tcl | package require Tcl 8.5
# Memoization wrapper
proc memoize {function value generator} {
variable memoize
set key $function,$value
if {![info exists memoize($key)]} {
set memoize($key) [uplevel 1 $generator]
}
return $memoize($key)
}
# The simplest recursive definition
proc tcl::mathfunc::catalan n {
if {[incr n 0] < 0} {error "must not be negative"}
memoize catalan $n {expr {
$n == 0 ? 1 : 2 * (2*$n - 1) * catalan($n - 1) / ($n + 1)
}}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Swift | Swift | import Foundation
let monthWidth = 20
let monthGap = 2
let dayNames = "Su Mo Tu We Th Fr Sa"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
func rpad(string: String, width: Int) -> String {
return string.count >= width ? string
: String(repeating: " ", count: width - string.count) + string
}
func lpad(string: String, width: Int) -> String {
return string.count >= width ? string
: string + String(repeating: " ", count: width - string.count)
}
func centre(string: String, width: Int) -> String {
if string.count >= width {
return string
}
let c = (width - string.count)/2
return String(repeating: " ", count: c) + string
+ String(repeating: " ", count: width - string.count - c)
}
func formatMonth(year: Int, month: Int) -> [String] {
let calendar = Calendar.current
let dc = DateComponents(year: year, month: month, day: 1)
let date = calendar.date(from: dc)!
let firstDay = calendar.component(.weekday, from: date) - 1
let range = calendar.range(of: .day, in: .month, for: date)!
let daysInMonth = range.count
var lines: [String] = []
lines.append(centre(string: dateFormatter.string(from: date), width: monthWidth))
lines.append(dayNames)
var padWidth = 2
var line = String(repeating: " ", count: 3 * firstDay)
for day in 1...daysInMonth {
line += rpad(string: String(day), width: padWidth)
padWidth = 3
if (firstDay + day) % 7 == 0 {
lines.append(line)
line = ""
padWidth = 2
}
}
if line.count > 0 {
lines.append(lpad(string: line, width: monthWidth))
}
return lines
}
func printCentred(string: String, width: Int) {
print(rpad(string: string, width: (width + string.count)/2))
}
public func printCalendar(year: Int, width: Int) {
let months = min(12, max(1, (width + monthGap)/(monthWidth + monthGap)))
let lineWidth = monthWidth * months + monthGap * (months - 1)
printCentred(string: "[Snoopy]", width: lineWidth)
printCentred(string: String(year), width: lineWidth)
var firstMonth = 1
while firstMonth <= 12 {
if firstMonth > 1 {
print()
}
let lastMonth = min(12, firstMonth + months - 1)
let monthCount = lastMonth - firstMonth + 1
var lines: [[String]] = []
var lineCount = 0
for month in firstMonth...lastMonth {
let monthLines = formatMonth(year: year, month: month)
lineCount = max(lineCount, monthLines.count)
lines.append(monthLines)
}
for i in 0..<lineCount {
var line = ""
for month in 0..<monthCount {
if month > 0 {
line.append(String(repeating: " ", count: monthGap))
}
line.append(i < lines[month].count ? lines[month][i]
: String(repeating: " ", count: monthWidth))
}
print(line)
}
firstMonth = lastMonth + 1
}
}
printCalendar(year: 1969, width: 80) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Pascal | Pascal | Program BullCow;
{$mode objFPC}
uses Math, SysUtils;
type
TFourDigit = array[1..4] of integer;
Procedure WriteFourDigit(fd: TFourDigit);
{ Write out a TFourDigit with no line break following. }
var
i: integer;
begin
for i := 1 to 4 do
begin
Write(fd[i]);
end;
end;
Function WellFormed(Tentative: TFourDigit): Boolean;
{ Does the TFourDigit avoid repeating digits? }
var
current, check: integer;
begin
Result := True;
for current := 1 to 4 do
begin
for check := current + 1 to 4 do
begin
if Tentative[check] = Tentative[current] then
begin
Result := False;
end;
end;
end;
end;
Function MakeNumber(): TFourDigit;
{ Make a random TFourDigit, keeping trying until it is well-formed. }
var
i: integer;
begin
for i := 1 to 4 do
begin
Result[i] := RandomRange(1, 9);
end;
if not WellFormed(Result) then
begin
Result := MakeNumber();
end;
end;
Function StrToFourDigit(s: string): TFourDigit;
{ Convert an (input) string to a TFourDigit. }
var
i: integer;
begin
for i := 1 to Length(s) do
begin
StrToFourDigit[i] := StrToInt(s[i]);
end;
end;
Function Wins(Num, Guess: TFourDigit): Boolean;
{ Does the guess win? }
var
i: integer;
begin
Result := True;
for i := 1 to 4 do
begin
if Num[i] <> Guess[i] then
begin
Result := False;
Exit;
end;
end;
end;
Function GuessScore(Num, Guess: TFourDigit): string;
{ Represent the score of the current guess as a string. }
var
i, j, bulls, cows: integer;
begin
bulls := 0;
cows := 0;
{ Count the cows and bulls. }
for i := 1 to 4 do
begin
for j := 1 to 4 do
begin
if (Num[i] = Guess[j]) then
begin
{ If the indices are the same, that would be a bull. }
if (i = j) then
begin
bulls := bulls + 1;
end
else
begin
cows := cows + 1;
end;
end;
end;
end;
{ Format the result as a sentence. }
Result := IntToStr(bulls) + ' bulls, ' + IntToStr(cows) + ' cows.';
end;
Function GetGuess(): TFourDigit;
{ Get a well-formed user-supplied TFourDigit guess. }
var
input: string;
begin
WriteLn('Enter a guess:');
ReadLn(input);
{ Must be 4 digits. }
if Length(input) = 4 then
begin
Result := StrToFourDigit(input);
if not WellFormed(Result) then
begin
WriteLn('Four unique digits, please.');
Result := GetGuess();
end;
end
else
begin
WriteLn('Please guess a four-digit number.');
Result := GetGuess();
end;
end;
var
Num, Guess: TFourDigit;
Turns: integer;
begin
{ Initialize the randymnity. }
Randomize();
{ Make the secred number. }
Num := MakeNumber();
WriteLn('I have a secret number. Guess it!');
Turns := 0;
{ Guess until the user gets it. }
While True do
begin
Guess := GetGuess();
{ Count each guess as a turn. }
Turns := Turns + 1;
{ If the user won, tell them and ditch. }
if Wins(Num, Guess) then
begin
WriteLn('You won in ' + IntToStr(Turns) + ' tries.');
Write('The number was ');
WriteFourDigit(Num);
WriteLn('!');
Exit;
end
else { Otherwise, score it and get a new guess. }
begin
WriteLn(GuessScore(Num, Guess));
end;
end;
end.
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #Lambdatalk | Lambdatalk |
{def caesar
{def caesar.alphabet {A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}}
{def caesar.delta
{lambda {:s :i :a}
{A.get {% {+ {A.in? {A.get :i :a} {caesar.alphabet}} 26 :s} 26}
{caesar.alphabet}}}}
{def caesar.loop
{lambda {:s :a :b :n :i}
{if {> :i :n}
then :b
else {caesar.r :s
:a
{A.set! :i {caesar.delta :s :i :a} :b}
:n
{+ :i 1}} }}}
{lambda {:shift :txt}
{let { {:s :shift}
{:t {S.replace [^A-Z] by in :txt}} }
{A.join {caesar.loop :s
{A.split :t}
{A.new}
{- {W.length :t} 1}
0 }}}}}
-> caesar
{def text VENI, VIDI, VICI}
-> text
{S.map {lambda {:i} {br}:i: {caesar :i {text}}}
{S.serie 0 26}}
->
0: VENIVIDIVICI
1: WFOJWJEJWJDJ
2: XGPKXKFKXKEK
3: YHQLYLGLYLFL
...
23: SBKFSFAFSFZF
24: TCLGTGBGTGAG
25: UDMHUHCHUHBH
26: VENIVIDIVICI
As a shorter alternative:
{def CAESAR
{def CAESAR.rot
{lambda {:shift :txt :alpha :i}
{A.get {% {+ {A.in? {A.get :i :txt} :alpha} 26 :shift} 26}
:alpha}}}
{def CAESAR.loop
{lambda {:shift :txt :alpha}
{S.map {CAESAR.rot :shift :txt :alpha}
{S.serie 0 {- {A.length :txt} 1}}} }}
{lambda {:shift :txt}
{S.replace \s by in
{CAESAR.loop :shift
{A.split {S.replace \s by in :txt}}
{A.split ABCDEFGHIJKLMNOPQRSTUVWXYZ}} }}}
-> CAESAR
{CAESAR 1 VENI VIDI VICI}
-> WFOJWJEJWJDJ
{CAESAR 25 WFOJWJEJWJDJ}
-> VENIVIDIVICI
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Sidef | Sidef | foo(); # without arguments
foo(1, 2); # with two arguments
foo(args...); # with a variable number of arguments
foo(name: 'Bar', age: 42); # with named arguments
var f = foo; # store the function foo inside 'f'
var result = f(); # obtain the return value of a function
var arr = [1,2,3];
foo(arr); # the arguments are passed by object-reference |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #TI-83_BASIC | TI-83 BASIC | :For(I,1,15
:Disp (2I)!/((I+1)!I!
:End |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.
THE REAL PROGRAMMER'S NATURAL HABITAT
"Taped to the wall is a line-printer Snoopy calender for the year 1969."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Tcl | Tcl | package require Tcl 8.5
# Produce information about the days in a month, without any assumptions about
# what those days actually are.
proc calMonthDays {timezone locale year month} {
set days {}
set moment [clock scan [format "%04d-%02d-00 12:00" $year $month] \
-timezone $timezone -locale $locale -format "%Y-%m-%d %H:%M"]
while 1 {
set moment [clock add $moment 1 day]
lassign [clock format $moment -timezone $timezone -locale $locale \
-format "%m %d %u"] m d dow
if {[scan $m %d] != $month} {
return $days
}
lappend days $moment [scan $d %d] $dow
}
}
proc calMonth {year month timezone locale} {
set dow 0
set line ""
set lines {}
foreach {t day dayofweek} [calMonthDays $timezone $locale $year $month] {
if {![llength $lines]} {lappend lines $t}
if {$dow > $dayofweek} {
lappend lines [string trimright $line]
set line ""
set dow 0
}
while {$dow < $dayofweek-1} {
append line " "
incr dow
}
append line [format "%2d " $day]
set dow $dayofweek
}
lappend lines [string trimright $line]
}
proc cal3Month {year month timezone locale} {
# Extract the month data
set d1 [lassign [calMonth $year $month $timezone $locale] t1]; incr month
set d2 [lassign [calMonth $year $month $timezone $locale] t2]; incr month
set d3 [lassign [calMonth $year $month $timezone $locale] t3]
# Print the header line of month names
foreach t [list $t1 $t2 $t3] {
set m [clock format $t -timezone $timezone -locale $locale -format "%B"]
set l [expr {10 + [string length $m]/2}]
puts -nonewline [format "%-25s" [format "%*s" $l $m]]
}
puts ""
# Print the month days
foreach l1 $d1 l2 $d2 l3 $d3 {
puts [format "%-25s%-25s%s" $l1 $l2 $l3]
}
}
proc cal {{year ""} {timezone :localtime} {locale en}} {
if {$year eq ""} {
set year [clock format [clock seconds] -format %Y]
}
puts [format "%40s" "-- $year --"]
foreach m {1 4 7 10} {
puts ""
cal3Month $year $m $timezone $locale
}
}
proc snoopy {} {
puts [format "%43s\n" {[Snoopy Picture]}]
}
snoopy
cal |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Perl | Perl | use Data::Random qw(rand_set);
use List::MoreUtils qw(uniq);
my $size = 4;
my $chosen = join "", rand_set set => ["1".."9"], size => $size;
print "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ( my $guesses = 1; ; $guesses++ ) {
my $guess;
while (1) {
print "\nNext guess [$guesses]: ";
$guess = <STDIN>;
chomp $guess;
checkguess($guess) and last;
print "$size digits, no repetition, no 0... retry\n";
}
if ( $guess eq $chosen ) {
print "You did it in $guesses attempts!\n";
last;
}
my $bulls = 0;
my $cows = 0;
for my $i (0 .. $size-1) {
if ( substr($guess, $i, 1) eq substr($chosen, $i, 1) ) {
$bulls++;
} elsif ( index($chosen, substr($guess, $i, 1)) >= 0 ) {
$cows++;
}
}
print "$cows cows, $bulls bulls\n";
}
sub checkguess
{
my $g = shift;
return uniq(split //, $g) == $size && $g =~ /^[1-9]{$size}$/;
} |
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".
This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.
Related tasks
Rot-13
Substitution Cipher
Vigenère Cipher/Cryptanalysis
| #langur | langur | val .rot = f(.s, .key) {
cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
}
val .s = "A quick brown fox jumped over something."
val .key = 3
writeln " original: ", .s
writeln "encrypted: ", .rot(.s, .key)
writeln "decrypted: ", .rot(.rot(.s, .key), -.key) |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #Smalltalk | Smalltalk | f valueWithArguments: arguments. |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
Calling a function with named arguments
Using a function in statement context
Using a function in first-class context within an expression
Obtaining the return value of a function
Distinguishing built-in functions and user-defined functions
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
This task is not about defining functions.
| #SSEM | SSEM | 00110000000000100000000000000000 10. -12 to c
10110000000000000000000000000000 11. 13 to CI
11001111111111111111111111111111 12. -13
11001000000000000000000000000000 13. 19 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.