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/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 random... | #Golo | Golo | #!/usr/bin/env golosh
----
This module is the Bulls and Cows game.
----
module Bullsandcows
import gololang.Decorators
import gololang.Functions
import gololang.IO
import java.util
function main = |args| {
while true {
let secret = create4RandomNumbers()
println("Welcome to Bulls And Cows")
while true... |
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... | #ERRE | ERRE |
PROGRAM CAESAR
!$INCLUDE="PC.LIB"
PROCEDURE CAESAR(TEXT$,KY%->CY$)
LOCAL I%,C%
FOR I%=1 TO LEN(TEXT$) DO
C%=ASC(MID$(TEXT$,I%))
IF (C% AND $1F)>=1 AND (C% AND $1F)<=26 THEN
C%=(C% AND $E0) OR (((C% AND $1F)+KY%-1) MOD 26+1)
CHANGE(TEXT$,I%,CHR$(C%)->TEXT$)
END IF
END ... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #VBScript | VBScript | e0 = 0 : e = 2 : n = 0 : fact = 1
While (e - e0) > 1E-15
e0 = e
n = n + 1
fact = fact * 2*n * (2*n + 1)
e = e + (2*n + 2)/fact
Wend
WScript.Echo "Computed e = " & e
WScript.Echo "Real e = " & Exp(1)
WScript.Echo "Error = " & (Exp(1) - e)
WScript.Echo "Number of iterations = " & n |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Verilog | Verilog | module main;
real n, n1;
real e1, e;
initial begin
n = 1.0;
n1 = 1.0;
e1 = 0.0;
e = 1.0;
while (e != e1) begin
e1 = e;
e = e + (1.0 / n);
n1 = n1 + 1;
n = n * n1;
end
$display("The value of e = ", e);
$finish ;
end
endmodule |
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
C... | #langur | langur | .x()
# call user-defined function |
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... | #Phix | Phix | with javascript_semantics
-- returns inf/-nan for n>85, and needs the rounding for n>=14, accurate to n=29
function catalan1(integer n)
return floor(factorial(2*n)/(factorial(n+1)*factorial(n))+0.5)
end function
-- returns inf for n>519, accurate to n=30:
function catalan2(integer n) -- NB: very slow!
atom res =... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Ring | Ring |
load "stdlib.ring"
decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
brazil = []
brazilOdd = []
brazilPrime = []
num1 = 0
num2 = 0
num3 = 0
limit = 20
see "working..." + nl
for n = 1 to 2802
for m = 2 to 16
flag = 1
b... |
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 fo... | #1._Grid_structure_functions | 1. Grid structure functions | DataGrid[
rowHeights:{__Integer},
colWidths:{__Integer},
spacings:{_Integer,_Integer},
borderWidths:{{_Integer,_Integer},{_Integer,_Integer}},
options_Association,
data:{__List?MatrixQ}]:=
With[
(*Need to make sure we have sensible defaults for the decoration options.*)
{alignment=Lookup[options,"... |
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 wi... | #R | R |
# plotmat(): Simple plotting using a square matrix mat (filled with 0/1). v. 8/31/16
# Where: mat - matrix; fn - file name; clr - color; ttl - plot title;
# dflg - writing dump file flag (0-no/1-yes): psz - picture size.
plotmat <- function(mat, fn, clr, ttl, dflg=0, psz=600) {
m <- nrow(mat); d <- 0;
X=NU... |
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 random... | #Groovy | Groovy | class BullsAndCows {
static void main(args) {
def inputReader = System.in.newReader()
def numberGenerator = new Random()
def targetValue
while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue
def targetStr = targetValue.toString()
de... |
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... | #Euphoria | Euphoria |
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
--usage eui caesar ->default text, key and encode flag
--usage eui caesar 'Text with spaces and punctuation!' 5 D
--If text has imbedded spaces must use apostophes instead of quotes so all punctuation works
--key = integer from 1 to 25, defaults to 13
--flag = ... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Visual_Basic_.NET | Visual Basic .NET | Imports System, System.Numerics, System.Math, System.Console
Module Program
Function CalcE(ByVal nDigs As Integer) As String
Dim pad As Integer = Round(Log10(nDigs)), n = 1,
f As BigInteger = BigInteger.Pow(10, nDigs + pad), e = f + f
Do : n+= 1 : f /= n : e += f : Loop While f > n
... |
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
C... | #Latitude | Latitude | foo (1, 2, 3). ; (1) Ordinary call
foo (). ; (2) No arguments
foo. ; (3) Equivalent to (2)
foo (1). ; (4) Single-argument function
foo 1. ; (5) Equivalent to (4)
foo (bar). ; (6) Parentheses necessary here since bar is not a literal
foo: 1, 2, 3. ; (7) Alternative syntax, equivalent ... |
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... | #PHP | PHP | <?php
class CatalanNumbersSerie
{
private static $cache = array(0 => 1);
private function fill_cache($i)
{
$accum = 0;
$n = $i-1;
for($k = 0; $k <= $n; $k++)
{
$accum += $this->item($k)*$this->item($n-$k);
}
self::$cache[$i] = $accum;
}
function item($i)
{
if (!isset(s... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Ruby | Ruby | def sameDigits(n,b)
f = n % b
while (n /= b) > 0 do
if n % b != f then
return false
end
end
return true
end
def isBrazilian(n)
if n < 7 then
return false
end
if n % 2 == 0 then
return true
end
for b in 2 .. n - 2 do
if sameDigits(... |
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 fo... | #2._Calendar_data_functions | 2. Calendar data functions | (*Mathematica makes it easy to get month names and day names for several standard calendars.*)
MonthNames[]:=MonthNames["Gregorian"];
MonthNames[calType_]:=Lookup[CalendarData[calType,"PropertyAssociation"],"MonthNames"];
WeekdayNames[]:=WeekdayNames["Gregorian"];
WeekdayNames[calType_]:=Lookup[CalendarData[calType,"... |
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 wi... | #Racket | Racket | #lang racket
(require 2htdp/image)
;; The unsafe fixnum ops are faster than the checked ones,
;; but if you get anything wrong with them, they'll bite.
;; If you experience any problems reactivate the
;; (require racket/fixnum) and instead of the unsafe requirement
;; below...
;; we have tested this...
#;(require r... |
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 wi... | #Raku | Raku | constant size = 100;
constant particlenum = 1_000;
constant mid = size div 2;
my $spawnradius = 5;
my @map;
sub set($x, $y) {
@map[$x][$y] = True;
}
sub get($x, $y) {
return @map[$x][$y] || False;
}
set(mid, mid);
my @blocks = " ","\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]","\c[FULL BLOCK]";
su... |
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 random... | #Haskell | Haskell | import Data.List (partition, intersect, nub)
import Control.Monad
import System.Random (StdGen, getStdRandom, randomR)
import Text.Printf
numberOfDigits = 4 :: Int
main = bullsAndCows
bullsAndCows :: IO ()
bullsAndCows = do
digits <- getStdRandom $ pick numberOfDigits ['1' .. '9']
putStrLn "Guess away!"
... |
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... | #F.23 | F# | module caesar =
open System
let private cipher n s =
let shift c =
if Char.IsLetter c then
let a = (if Char.IsLower c then 'a' else 'A') |> int
(int c - a + n) % 26 + a |> char
else c
String.map shift s
let encrypt n = cipher n
... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Vlang | Vlang | import math
const epsilon = 1.0e-15
fn main() {
mut fact := u64(1)
mut e := 2.0
mut n := u64(2)
for {
e0 := e
fact *= n
n++
e += 1.0 / f64(fact)
if math.abs(e - e0) < epsilon {
break
}
}
println("e = ${e:.15f}")
} |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Wren | Wren | var epsilon = 1e-15
var fact = 1
var e = 2
var n = 2
while (true) {
var e0 = e
fact = fact * n
n = n + 1
e = e + 1/fact
if ((e - e0).abs < epsilon) break
}
System.print("e = %(e)") |
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
C... | #LFE | LFE |
(defun my-func()
(: io format '"I get called with NOTHING!~n"))
|
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... | #Picat | Picat |
table
factorial(0) = 1.
factorial(N) = N * factorial(N - 1).
catalan1(N) = factorial(2 * N) // (factorial(N + 1) * factorial(N)).
catalan2(0) = 1.
catalan2(N) = 2 * (2 * N - 1) * catalan2(N - 1) // (N + 1).
main =>
foreach (I in 0..14)
printf("%d. %d = %d\n", I, catalan1(I), catalan2(I))
end... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Rust | Rust |
fn same_digits(x: u64, base: u64) -> bool {
let f = x % base;
let mut n = x;
while n > 0 {
if n % base != f {
return false;
}
n /= base;
}
true
}
fn is_brazilian(x: u64) -> bool {
if x < 7 {
return false;
};
if x % 2 == 0 {
return t... |
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 fo... | #3._Output_configuration | 3. Output configuration | WidestFitDimensions[
targetWidth_Integer,
columnSpacings_Integer,
leftRightBorderWidths:{_Integer,_Integer},
data:{__List?MatrixQ}]:=
With[
{widths=Last/@Dimensions/@data,
fullWidthOfRow=Total[ArrayPad[Riffle[#,columnSpacings],leftRightBorderWidths,1]]&},
With[
{fullWidthOfGrid=Max[fullWidt... |
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 wi... | #REXX | REXX | /*REXX program animates and displays Brownian motion of dust in a field (with one seed).*/
mote = '·' /*character for a loose mote (of dust).*/
hole = ' ' /* " " an empty spot in field.*/
seedPos = 0 ... |
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 random... | #Hy | Hy | (import random)
(def +size+ 4)
(def +digits+ "123456789")
(def +secret+ (random.sample +digits+ +size+))
(while True
(while True
(setv guess (list (distinct (raw-input "Enter a guess: "))))
(when (and
(= (len guess) +size+)
(all (map (fn [c] (in c +digits+)) guess)))
(break))
(pr... |
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... | #Factor | Factor | USING: io kernel locals math sequences unicode.categories ;
IN: rosetta-code.caesar-cipher
:: cipher ( n s -- s' )
[| c |
c Letter? [
c letter? CHAR: a CHAR: A ? :> a
c a - n + 26 mod a +
]
[ c ] if
] :> shift
s [ shift call ] map ;
: encrypt ( n s -- s' )... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #XPL0 | XPL0 | real N, E, E0, F; \index, Euler numbers, factorial
[Format(1, 16); \show 16 places after decimal point
N:= 1.0; E:= 1.0; F:= 1.0;
loop [E0:= E;
E:= E + 1.0/F;
if E = E0 then quit;
N:= N + 1.0;
F:= F*N;
];
RlOut(0, E); CrLf(0);
IntOut(0, fix(N)); Text(0, " ite... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Zig | Zig |
const std = @import("std");
const math = std.math;
const stdout = std.io.getStdOut().writer();
pub fn main() !void {
var n: u32 = 0;
var state: u2 = 0;
var p0: u64 = 0;
var q0: u64 = 1;
var p1: u64 = 1;
var q1: u64 = 0;
while (true) {
var a: u64 = undefined;
switch (state... |
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
C... | #Liberty_BASIC | Liberty BASIC |
'Call a function - Liberty BASIC
'First, function result could not be discarded
' that is, you cannot do "f(x)" as a separate statement
'Calling a function that requires no arguments
res = f() 'brackets required
'Calling a function with a fixed number of arguments
res = g(x)
res = h(x,y)
'Calling a function w... |
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... | #PicoLisp | PicoLisp | # Factorial
(de fact (N)
(if (=0 N)
1
(* N (fact (dec N))) ) )
# Directly
(de catalanDir (N)
(/ (fact (* 2 N)) (fact (inc N)) (fact N)) )
# Recursively
(de catalanRec (N)
(if (=0 N)
1
(cache '(NIL) N # Memoize
(sum
'((I) (* (catalanRec I) (catalanRec (- N I 1))... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Scala | Scala | object BrazilianNumbers {
private val PRIME_LIST = List(
2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, ... |
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 fo... | #Nim | Nim | import times
import strformat
proc printCalendar(year, nCols: int) =
var rows = 12 div nCols
var date = initDateTime(1, mJan, year, 0, 0, 0, utc())
if rows mod nCols != 0:
inc rows
var offs = getDayOfWeek(date.monthday, date.month, date.year).int
var mons: array[12, array[8, string]]
for m in 0..11:
... |
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 wi... | #Ring | Ring |
# Project : Brownian tree
load "stdlib.ring"
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("")
setgeometry(100,100,800,600)
label1 = new qlabel(win1) {
setgeometry(10,10,800,60... |
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 random... | #Icon_and_Unicon | Icon and Unicon | procedure main()
digits := "123456789"
every !digits :=: ?digits
num := digits[1+:4]
repeat if score(num, getGuess(num)) then break
write("Good job.")
end
procedure getGuess(num)
repeat {
writes("Enter a guess: ")
guess := read() | stop("Quitter!")
if *(guess ** '123456... |
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... | #Fantom | Fantom |
class Main
{
static Int shift (Int char, Int key)
{
newChar := char + key
if (char >= 'a' && char <= 'z')
{
if (newChar - 'a' < 0) { newChar += 26 }
if (newChar - 'a' >= 26) { newChar -= 26 }
}
else if (char >= 'A' && char <= 'Z')
{
if (newChar - 'A' < 0) { newChar +=... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #zkl | zkl | const EPSILON=1.0e-15;
fact,e,n := 1, 2.0, 2;
do{
e0:=e;
fact*=n; n+=1;
e+=1.0/fact;
}while((e - e0).abs() >= EPSILON);
println("e = %.15f".fmt(e)); |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET p=13: REM precision, or the number of terms in the Taylor expansion, from 0 to 33...
20 LET k=1: REM ...the Spectrum's maximum expressible precision is reached at p=13, while...
30 LET e=0: REM ...the factorial can't go any higher than 33
40 FOR x=1 TO p
50 LET e=e+1/k
60 LET k=k*x
70 NEXT x
80 PRINT e
90 PRINT ... |
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
C... | #Lingo | Lingo | foo()
-- or alternatively:
call(#foo, _movie) |
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... | #PL.2FI | PL/I | catalan: procedure options (main); /* 23 February 2012 */
declare (i, n) fixed;
put skip list ('How many catalan numbers do you want?');
get list (n);
do i = 0 to n;
put skip list (c(i));
end;
c: procedure (n) recursive returns (fixed decimal (15));
declare n fixed;
if n <= 1 then r... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Sidef | Sidef | func is_Brazilian_prime(q) {
static L = Set()
static M = 0
return true if L.has(q)
return false if (q < M)
var N = (q<1000 ? 1000 : 2*q)
for K in (primes(3, ilog2(N+1))) {
for n in (2 .. iroot(N-1, K-1)) {
var p = (n**K - 1)/(n-1)
L << p if (p<N && p.is_p... |
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 fo... | #OCaml | OCaml | #load "unix.cma"
let lang = "en" (* language: English *)
let usage () =
Printf.printf "Usage:\n%s\n" Sys.argv.(0)
let month_pattern =
[
[ 0; 4; 8 ];
[ 1; 5; 9 ];
[ 2; 6; 10 ];
[ 3; 7; 11 ];
(*
[ 0; 1; 2; 3; 4; 5 ];
[ 6; 7; 8; 9; 10; 11 ];
[ 0; 1; 2; ... |
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 wi... | #Ruby | Ruby | require 'rubygems'
require 'RMagick'
NUM_PARTICLES = 1000
SIZE = 800
def draw_brownian_tree world
# set the seed
world[rand SIZE][rand SIZE] = 1
NUM_PARTICLES.times do
# set particle's position
px = rand SIZE
py = rand SIZE
loop do
# randomly choose a direction
dx = ra... |
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 random... | #J | J | require 'misc'
plural=: conjunction define
(":m),' ',n,'s'#~1~:m
)
bullcow=:monad define
number=. 1+4?9
whilst. -.guess-:number do.
guess=. 0 "."0 prompt 'Guess my number: '
if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do.
if. 0=#guess do.
smoutput 'Giving up.'
return.
... |
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... | #Fhidwfe | Fhidwfe |
lowers = ['a','z']
uppers = ['A','Z']
function void caesar_encode(message:ptr key:uint) {
len = strlen$ message
for uint [0u,len) with index {
temp = deref_ubyte$ + message index
if in temp lowers {
temp = + temp key// shift lowercase letters
if > temp 'z' {
temp = - temp 26ub
} ... |
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
C... | #Little | Little | // Calling a function that requires no arguments
void foo() {puts("Calling a function with no arguments");}
foo();
// Calling a function with a fixed number of arguments
abs(-36);
// Calling a function with optional arguments
puts(nonewline: "nonewline is an optional argument");
puts("\n");
// Calling a function ... |
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... | #Plain_TeX | Plain TeX | \newcount\n
\newcount\r
\newcount\x
\newcount\ii
\def\catalan#1{%
\n#1\advance\n by1\ii1\r1%
\loop{%
\x\ii%
\multiply\x by 2 \advance\x by -1 \multiply\x by 2%
\global\multiply\r by\x%
\global\advance\ii by1%
\global\divide\r by\ii%
} \ifnum\number\ii<\n\repeat%
\the\r
}
\rightskip=0pt plus1fil\parind... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean
Dim f As Integer = n Mod b : n \= b : While n > 0
If n Mod b <> f Then Return False Else n \= b
End While : Return True
End Function
Function isBrazilian(ByVal n As Integer) As Boolean
... |
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 fo... | #Perl | Perl | #!/usr/bin/perl -l
use strict; # https://rosettacode.org/wiki/Calendar
use warnings;
use Time::Local;
my $year = shift // 1969;
my $width = shift // 80;
my $columns = int +($width + 2) / 22 or die "width too short at $width";
print map { center($_, $width), "\n" } '<reserved for snoopy>', $year;
my @months = qw( Ja... |
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 wi... | #Run_BASIC | Run BASIC | numParticles = 3000
dim canvas(201,201)
graphic #g, 200,200
#g fill("blue")
canvas(rnd(1) * 100 , rnd(1) * 200) = 1 'start point
for i = 1 To numParticles
x = (rnd(1) * 199) + 1
y = (rnd(1) * 199) + 1
while canvas(x+1, y+1)+canvas(x, y+1)+canvas(x+1, y)+canvas(x-1, y-1)+canvas(x-1, y)+canvas(x, y-1) = 0
... |
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 random... | #Java | Java | import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class BullsAndCows{
public static void main(String[] args){
Random gen= new Random();
int target;
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
String targetStr = target +"";
boolean guessed = false;
... |
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... | #Forth | Forth | : ceasar ( c n -- c )
over 32 or [char] a -
dup 0 26 within if
over + 25 > if 26 - then +
else 2drop then ;
: ceasar-string ( n str len -- )
over + swap do i c@ over ceasar i c! loop drop ;
: ceasar-inverse ( n -- 'n ) 26 swap - 26 mod ;
2variable test
s" The five boxing wizards jump quickly!" test 2!... |
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
C... | #Lua | Lua | -- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped.
function fixed (a, b, c) print(a, b, c) end
fixed() --> nil nil nil
fixed(1, 2, 3, 4, 5) --> 1 2 3
-- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of val... |
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... | #PowerShell | PowerShell |
function Catalan([uint64]$m) {
function fact([bigint]$n) {
if($n -lt 2) {[bigint]::one}
else{2..$n | foreach -Begin {$prod = [bigint]::one} -Process {$prod = [bigint]::Multiply($prod,$_)} -End {$prod}}
}
$fact = fact $m
$fact1 = [bigint]::Multiply($m+1,$fact)
[bigint]::divide((fact... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Vlang | Vlang | fn same_digits(nn int, b int) bool {
f := nn % b
mut n := nn/b
for n > 0 {
if n%b != f {
return false
}
n /= b
}
return true
}
fn is_brazilian(n int) bool {
if n < 7 {
return false
}
if n%2 == 0 && n >= 8 {
return true
}
for b... |
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 fo... | #Phix | Phix | with javascript_semantics
constant year = 1969
include builtins\timedate.e
function centre(string s, integer width)
integer gap = width-length(s),
left = floor(gap/2),
right = gap-left
return repeat(' ',left) & s & repeat(' ',right)
end function
function one_month(integer year, int... |
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 wi... | #Rust | Rust |
extern crate image;
extern crate rand;
use image::ColorType;
use std::cmp::{min, max};
use std::env;
use std::path::Path;
use std::process;
use rand::Rng;
fn help() {
println!("Usage: brownian_tree <output_path> <mote_count> <edge_length>");
}
fn main() {
let args: Vec<String> = env::args().collect();... |
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 random... | #JavaScript | JavaScript | #!/usr/bin/env js
function main() {
var len = 4;
playBullsAndCows(len);
}
function playBullsAndCows(len) {
var num = pickNum(len);
// print('The secret number is:\n ' + num.join('\n '));
showInstructions(len);
var nGuesses = 0;
while (true) {
nGuesses++;
var guess = get... |
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... | #Fortran | Fortran | program Caesar_Cipher
implicit none
integer, parameter :: key = 3
character(43) :: message = "The five boxing wizards jump quickly"
write(*, "(2a)") "Original message = ", message
call encrypt(message)
write(*, "(2a)") "Encrypted message = ", message
call decrypt(message)
write(*, "(2a)") "Dec... |
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
C... | #Luck | Luck | /* Calling a function that requires no arguments */
f();;
/* Calling a function with a fixed number of arguments */
f(1,2);;
/* Calling a function with optional arguments
Note: defining the function is cumbersome but will get easier in future versions. */
f(1,2,new {default with x=3, y=4});;
/* Calling a func... |
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... | #Prolog | Prolog | catalan(N) :-
length(L1, N),
L = [1 | L1],
init(1,1,L1),
numlist(0, N, NL),
maplist(my_write, NL, L).
init(_, _, []).
init(V, N, [H | T]) :-
N1 is N+1,
H is 2 * (2 * N - 1) * V / N1,
init(H, N1, T).
my_write(N, V) :-
format('~w : ~w~n', [N, V]). |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #Wren | Wren | import "/math" for Int
var sameDigits = Fn.new { |n, b|
var f = n % b
n = (n/b).floor
while (n > 0) {
if (n%b != f) return false
n = (n/b).floor
}
return true
}
var isBrazilian = Fn.new { |n|
if (n < 7) return false
if (n%2 == 0 && n >= 8) return true
for (b in 2...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 fo... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
32 var space
def bksp /# -- backspace #/
8 tochar print
enddef
def floor
.5 + int
enddef
def center
tostr align
enddef
def startday /# year -- day of the week of january 1 #/
1 - >ps
tps 365 * tps 4 / floor + tps 100 / floor - ps> 400 / floor + 7 mod
enddef
... |
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 wi... | #Scala | Scala | import java.awt.Graphics
import java.awt.image.BufferedImage
import javax.swing.JFrame
import scala.collection.mutable.ListBuffer
object BrownianTree extends App {
val rand = scala.util.Random
class BrownianTree extends JFrame("Brownian Tree") with Runnable {
setBounds(100, 100, 400, 300)
val img = ... |
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 random... | #Julia | Julia | function cowsbulls()
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
You get one bull for every right number in the right position.\n
You get one cow for every right number, but in the wrong position.\n
Enter 'n' to pick a new number and 'q... |
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub Encrypt(s As String, key As Integer)
Dim c As Integer
For i As Integer = 0 To Len(s)
Select Case As Const s[i]
Case 65 To 90
c = s[i] + key
If c > 90 Then c -= 26
s[i] = c
Case 97 To 122
c = s[i] + key
If c > 122 Then c -= 26
... |
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
C... | #M2000_Interpreter | M2000 Interpreter | // Calling a function that requires no arguments
ModuleA ' introduce a namespace can have modules/functions/subs, anything inside, and threads.
Call FunctionA() ' introduce a namespace can have modules/functions/subs, anything inside.
Call LambdaA() ' introduce a namespace can have modules/functions/subs, anyt... |
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... | #PureBasic | PureBasic | ; saving the division for last ensures we divide the largest
; numerator by the smallest denominator
Procedure.q CatalanNumber(n.q)
If n<0:ProcedureReturn 0:EndIf
If n=0:ProcedureReturn 1:EndIf
ProcedureReturn (2*(2*n-1))*CatalanNumber(n-1)/(n+1)
EndProcedure
ls=25
rs=12
a.s=""
a.s+LSet(RSet("n",rs),ls)+"CatalanN... |
http://rosettacode.org/wiki/Brazilian_numbers | Brazilian numbers | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent... | #zkl | zkl | fcn isBrazilian(n){
foreach b in ([2..n-2]){
f,m := n%b, n/b;
while(m){
if((m % b)!=f) continue(2);
m/=b;
}
return(True);
}
False
}
fcn isBrazilianW(n){ isBrazilian(n) and n or Void.Skip } |
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 fo... | #PicoLisp | PicoLisp | (de cal (Year)
(prinl "====== " Year " ======")
(for Dat (range (date Year 1 1) (date Year 12 31))
(let D (date Dat)
(tab (3 3 4 8)
(when (= 1 (caddr D))
(get *Mon (cadr D)) )
(caddr D)
(day Dat *Day)
(when (=0 (% (inc Dat) 7))
... |
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 wi... | #Scheme | Scheme | ; Save bitmap to external file
(define (save-pbm bitmap filename)
(define f (open-output-file filename))
(simple-format f "P1\n~A ~A\n"
(list-ref (array-dimensions bitmap) 0)
(list-ref (array-dimensions bitmap) 1))
(do ((c 0 (+ c 1))) ((eqv? c (list-ref (array-dimensions bitmap) 1)))
(do ((r 0 (+ r 1))) ((eqv? ... |
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 random... | #Kotlin | Kotlin | // version 1.1.2
import java.util.Random
const val MAX_GUESSES = 20 // say
fun main(args: Array<String>) {
val r = Random()
var num: String
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
do {
num = (1234 + r.nextInt(8643)).toString()
} while ('0... |
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... | #Gambas | Gambas | Public Sub Main()
Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte 'Counter
Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQR... |
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
C... | #Maple | Maple | f() |
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... | #Python | Python | from math import factorial
import functools
def memoize(func):
cache = {}
def memoized(key):
# Returned, new, memoized version of decorated function
if key not in cache:
cache[key] = func(key)
return cache[key]
return functools.update_wrapper(memoized, func)
@me... |
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 fo... | #Pike | Pike | #!/bin/env pike
int main(int argc, array(string) argv)
{
object cal = Calendar;
object year;
string region = "us";
array date = argv[1..];
if (sizeof(date) && objectp(Calendar[date[0]]) && Calendar[date[0]]->Day)
{
cal = Calendar[date[0]];
date = Array.shift(date)[1];
}
... |
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 wi... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
const integer: SIZE is 300;
const integer: SCALE is 1;
const proc: genBrownianTree (in integer: fieldSize, in integer: numParticles) is func
local
var array array integer: world is 0 times 0 times 0;
var integer: px is 0;
var integ... |
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 wi... | #SequenceL | SequenceL | import <Utilities/Random.sl>;
import <Utilities/Sequence.sl>;
POINT ::= (X: int, Y: int);
RET_VAL ::= (World: int(2), Rand: RandomGenerator<int, int>, Point: POINT);
randomWalk(x, y, world(2), rand) :=
let
randX := getRandom(rand);
randY := getRandom(randX.Generator);
nextX := x + (randX.Value mod 3) - 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 random... | #Lasso | Lasso | [
define randomizer() => {
local(n = string)
while(#n->size < 4) => {
local(r = integer_random(1,9)->asString)
#n !>> #r ? #n->append(#r)
}
return #n
}
define cowbullchecker(n::string,a::string) => {
integer(#n) == integer(#a) ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
local(cowbull = map('cows'=0,'... |
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... | #GAP | GAP | CaesarCipher := function(s, n)
local r, c, i, lower, upper;
lower := "abcdefghijklmnopqrstuvwxyz";
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
r := "";
for c in s do
i := Position(lower, c);
if i <> fail then
Add(r, lower[RemInt(i + n - 1, 26) + 1]);
else
i := Position(upper, c);
if i <> fail then
Ad... |
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
C... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | 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
C... | #MATLAB_.2F_Octave | MATLAB / Octave |
% Calling a function that requires no arguments
function a=foo();
a=4;
end;
x = foo();
% Calling a function with a fixed number of arguments
function foo(a,b,c);
%% function definition;
end;
foo(x,y,z);
% Calling a function with optional argu... |
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... | #Quackery | Quackery | [ 1 over times [ over i 1+ + * ] nip ] is 2n!/n! ( n --> n )
[ times [ i 1+ / ] ] is /n! ( n --> n )
[ dup 2n!/n! swap 1+ /n! ] is catalan ( n --> n )
15 times [ i^ dup echo say " : " catalan echo cr ] |
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 fo... | #PL.2FI | PL/I |
calendar: procedure (year) options (main);
declare year character (4) varying;
declare (a, b, c) (0:5,0:6) character (3);
declare name_month(12) static character (9) varying initial (
'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE',
'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER',... |
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 wi... | #Sidef | Sidef | const size = 100
const mid = size>>1
const particlenum = 1000
var map = []
var spawnradius = 5
func set(x, y) {
map[x][y] = 1
}
func get(x, y) {
map[x][y] \\ 0
}
set(mid, mid)
var blocks = [
" ",
"\N{UPPER HALF BLOCK}",
"\N{LOWER HALF BLOCK}",
"\N{FULL BLOCK}"
]
func block(a, b) {
... |
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 random... | #Liberty_BASIC | Liberty BASIC |
do while len( secret$) <4
c$ =chr$( int( rnd( 1) *9) +49)
if not( instr( secret$, c$)) then secret$ =secret$ +c$
loop
print " Secret number has been guessed.... "; secret$
guesses = 0
[loop]
... |
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... | #GFA_Basic | GFA Basic |
'
' Caesar cypher
'
OPENW 1 ! Creates a window for handling input/output
CLEARW 1
INPUT "string to encrypt ";text$
INPUT "encryption key ";key%
encrypted$=@encrypt$(UPPER$(text$),key%)
PRINT "Encrypted: ";encrypted$
PRINT "Decrypted: ";@decrypt$(encrypted$,key%)
'
PRINT "(Press any key to end program.)"
~INP(2)
CL... |
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
C... | #Nanoquery | Nanoquery | // function with no arguments
no_args()
// function with fixed amount of arguments
three_args(a, b, c)
// nanoquery does not support optional, variable, or named arguments
// obtaining a return value
value = returns_value()
// checking if a function called "func" is user-defined
try
type(func)
p... |
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
C... | #Nemerle | Nemerle | // no arguments
f()
// fixed arguments
def f(a, b) { ... } // as an aside, functions defined with 'def' use type inference for parameters and return types
f(1, 'a')
// optional arguments
def f(a, b = 0) { ... }
f("hello")
f("goodbye", 2)
f("hey", b = 2) // using the name makes more sense if there's more than one op... |
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... | #R | R | catalan <- function(n) choose(2*n, n)/(n + 1)
catalan(0:15)
[1] 1 1 2 5 14 42 132 429 1430
[10] 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 fo... | #PowerShell | PowerShell |
Param([int]$Year = 1969)
Begin {
$COL_WIDTH = 21
$COLS = 3
$MONTH_COUNT = 12
$MONTH_LINES = 9
Function CenterStr([string]$s, [int]$lineSize) {
$padSize = [int](($lineSize - $s.Length) / 2)
($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ')
}
... |
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 wi... | #Simula | Simula | BEGIN
INTEGER NUM_PARTICLES;
INTEGER LINES, COLUMNS;
INTEGER SEED;
NUM_PARTICLES := 1000;
LINES := 46;
COLUMNS := 80;
SEED := ININT;
BEGIN
PROCEDURE DRAW_BROWNIAN_TREE(WORLD); INTEGER ARRAY WORLD;
BEGIN
INTEGER PX, PY; COMMENT PARTICLE VALUES ;
... |
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 random... | #Logo | Logo | to ok? :n
output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])
end
to init
do.until [make "hidden random 10000] [ok? :hidden]
end
to guess :n
if not ok? :n [print [Bad guess! (4 unique digits, 1-9)] stop]
localmake "bulls 0
localmake "cows 0
foreach :n [cond [
[[? = it... |
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... | #Go | Go | package main
import (
"fmt"
"strings"
)
type ckey struct {
enc, dec func(rune) rune
}
func newCaesar(k int) (*ckey, bool) {
if k < 1 || k > 25 {
return nil, false
}
rk := rune(k)
return &ckey{
enc: func(c rune) rune {
if c >= 'a' && c <= 'z'-rk || c >= 'A' &... |
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
C... | #Nim | Nim | proc no_args() =
discard
# call
no_args()
proc fixed_args(x, y) =
echo x
echo y
# calls
fixed_args(1, 2) # x=1, y=2
fixed_args 1, 2 # same call
1.fixed_args(2) # same call
proc opt_args(x=1.0) =
echo x
# calls
opt_args() # 1
opt_args(3.141) # 3.141
proc var_ar... |
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
C... | #OCaml | OCaml | f () |
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... | #Racket | Racket | #lang racket
(require planet2)
; (install "this-and-that") ; uncomment to install
(require memoize/memo)
(define/memo* (catalan m)
(if (= m 0)
1
(for/sum ([i m])
(* (catalan i) (catalan (- m i 1))))))
(map catalan (range 1 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 fo... | #Prolog | Prolog | % Write out the calender, because format can actually span multiple lines, it is easier
% to write out the static parts in place and insert the generated parts into that format.
write_calendar(Year) :-
month_x3_format(Year, 1, 2, 3, F1_3),
month_x3_format(Year, 4, 5, 6, F4_6),
month_x3_format(Year, 7, 8, 9, F7_9),
... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.