task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Clojure | Clojure |
(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))
|
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #COBOL | COBOL | identification division.
program-id. check-file-exist.
environment division.
configuration section.
repository.
function all intrinsic.
data division.
working-storage section.
01 skip pic 9 value 2.
01 file-name.
05 ... |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a ... | #F.23 | F# |
open System.Windows.Forms
open System.Drawing
open System
let sz = 300
let polygon = [Point(sz/2, int (float sz*(1.0-sin(Math.PI/3.0)))); Point(0, sz-1); Point(sz-1, sz-1)]
let bmp = new Bitmap(sz, sz)
let paint (p: Point) = bmp.SetPixel(p.X, p.Y, Color.Black)
let random = Random()
let seed = Point(int (random.... |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
import Network
import System.IO
import Control.Concurrent
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.Text.IO as T
import qualified Data.Map as M
import Data.Map (Map)
import Control.Monad.Reader
import Control.Monad.Error
import Control.Exception
imp... |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
ar... | #ooRexx | ooRexx | /*REXX ----------------------------------------------------------------
* 09.04.2014 Walter Pachl the REXX solution adapted for ooRexx
* which provides a function package rxMath
*--------------------------------------------------------------------*/
Numeric Digits 16
Numeric Fuzz 3; pi=rx... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Batch_File | Batch File |
@echo off
:: Supports all ASCII characters and codes from 34-126 with the exceptions of:
:: 38 &
:: 60 <
:: 62 >
:: 94 ^
:: 124 |
:_main
call:_toCode a
call:_toChar 97
pause>nul
exit /b
:_toCode
setlocal enabledelayedexpansion
set codecount=32
for /l %%i in (33,1,126) do (
set /a codecount+=1
cmd /c ex... |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #JavaScript | JavaScript |
const cholesky = function (array) {
const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0));
const L = zeros.map((row, r, xL) => row.map((v, c) => {
const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0);
return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - ... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #jq | jq | def count(stream; cond):
reduce stream as $i (0; if $i|cond then .+1 else . end);
def Months: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
# tostring
def birthday: "\(Months[.month-1]) \(.day)";
# Input: a Birthday
def mont... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Julia | Julia | const dates = [[15, "May"], [16, "May"], [19, "May"], [17, "June"], [18, "June"],
[14, "July"], [16, "July"], [14, "August"], [15, "August"], [17, "August"]]
uniqueday(parr) = filter(x -> count(y -> y[1] == x[1], parr) == 1, parr)
# At the start, they come to know that they have no unique day of month to identi... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Ruby | Ruby | require 'socket'
# A Workshop runs all of its workers, then collects their results. Use
# Workshop#add to add workers and Workshop#work to run them.
#
# This implementation forks some processes to run the workers in
# parallel. Ruby must provide Kernel#fork and 'socket' library must
# provide UNIXSocket.
#
# Why proc... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Kotlin | Kotlin | import java.util.PriorityQueue
fun main(args: Array<String>) {
// generic array
val ga = arrayOf(1, 2, 3)
println(ga.joinToString(prefix = "[", postfix = "]"))
// specialized array (one for each primitive type)
val da = doubleArrayOf(4.0, 5.0, 6.0)
println(da.joinToString(prefix = "[", postf... |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Pascal | Pascal | Program Combinations;
const
m_max = 3;
n_max = 5;
var
combination: array [0..m_max] of integer;
procedure generate(m: integer);
var
n, i: integer;
begin
if (m > m_max) then
begin
for i := 1 to m_max do
write (combination[i], ' ');
writeln;
end
else
for n := 1 to n_max do
... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Sather | Sather | if EXPR then
-- CODE
elsif EXPR then
-- CODE
else
-- CODE
end; |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Groovy | Groovy | class ChineseRemainderTheorem {
static int chineseRemainder(int[] n, int[] a) {
int prod = 1
for (int i = 0; i < n.length; i++) {
prod *= n[i]
}
int p, sm = 0
for (int i = 0; i < n.length; i++) {
p = prod.intdiv(n[i])
sm += a[i] * mulInv(... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Picat | Picat |
table
chowla(1) = 0.
chowla(2) = 0.
chowla(3) = 0.
chowla(N) = C, N>3 =>
Max = floor(sqrt(N)),
Sum = 0,
foreach (X in 2..Max, N mod X == 0)
Y := N div X,
Sum := Sum + X + Y
end,
if (N == Max * Max) then
Sum := Sum - Max
end,
C = Sum.
main =>
foreach (I in 1..3... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #PicoLisp | PicoLisp | (de accu1 (Var Key)
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
(push Var (cons Key 1)) )
Key )
(de factor (N)
(let
(R NIL
D 2
L (1 2 2 . (4 2 4 2 4 6 2 6 .))
M (sqrt N) )
(while (>= M D)
(if (=0 (% N D))
(setq M
(sqrt (... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Wren | Wren | class Church {
static zero { Fn.new { Fn.new { |x| x } } }
static succ(c) { Fn.new { |f| Fn.new { |x| f.call(c.call(f).call(x)) } } }
static add(c, d) { Fn.new { |f| Fn.new { |x| c.call(f).call(d.call(f).call(x)) } } }
static mul(c, d) { Fn.new { |f| c.call(d.call(f)) } }
static pow(c, e) { ... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Lasso | Lasso |
define mytype => type {
data
public id::integer = 0,
public val::string = '',
public rand::integer = 0
public onCreate() => {
// "onCreate" runs when instance created, populates .rand
.rand = math_random(50,1)
}
public asString() => {
return 'has a value of: "'+.val+'" and a rand number of "'+.ran... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #LFE | LFE |
(defmodule simple-object
(export all))
(defun fish-class (species)
"
This is the constructor used internally, once the children and fish id are
known.
"
(let ((habitat '"water"))
(lambda (method-name)
(case method-name
('habitat
(lambda (self) habitat))
('species
... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Objective-C | Objective-C |
type point = { x : float; y : float }
let cmpPointX (a : point) (b : point) = compare a.x b.x
let cmpPointY (a : point) (b : point) = compare a.y b.y
let distSqrd (seg : (point * point) option) =
match seg with
| None -> max_float
| Some(line) ->
let a = fst line in
let b = snd line in
... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Tcl | Tcl | package require Tcl 8.6; # Just for tailcall command
# Builds a value-capturing closure; does NOT couple variables
proc closure {script} {
set valuemap {}
foreach v [uplevel 1 {info vars}] {
lappend valuemap [list $v [uplevel 1 [list set $v]]]
}
set body [list $valuemap $script [uplevel 1 {namespace cu... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #Java | Java | import java.util.Objects;
public class Circles {
private static class Point {
private final double x, y;
public Point(Double x, Double y) {
this.x = x;
this.y = y;
}
public double distanceFrom(Point other) {
double dx = x - other.x;
... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #J | J | ELEMENTS=: _4 |. 2 # ;:'Wood Fire Earth Metal Water'
YEARS=: 1935 1938 1968 1972 1976 2017
ANIMALS=: _4 |. ;:'Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig'
YINYANG=: ;:'yang yin'
cz=: (|~ #)~ { [
ANIMALS cz YEARS
┌───┬─────┬──────┬───┬──────┬───────┐
│Pig│Tiger│Monkey│Rat│D... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #CoffeeScript | CoffeeScript |
fs = require 'fs'
path = require 'path'
root = path.resolve '/'
current_dir = __dirname
filename = 'input.txt'
dirname = 'docs'
local_file = path.join current_dir, filename
local_dir = path.join current_dir, dirname
root_file = path.join root, filename
root_dir = path.join root, dirname
for p in [ local_file,... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Common_Lisp | Common Lisp | (if (probe-file (make-pathname :name "input.txt"))
(print "rel file exists"))
(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))
(print "abs file exists"))
(if (directory (make-pathname :directory '(:relative "docs")))
(print "rel directory exists")
(print "rel directory is ... |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a ... | #Fortran | Fortran |
PROGRAM CHAOS
IMPLICIT NONE
REAL, DIMENSION(3):: KA, KN ! Koordinates old/new
REAL, DIMENSION(3):: DA, DB, DC ! Triangle
INTEGER:: I, Z
INTEGER, PARAMETER:: UT = 17
! Define corners of triangle
DA = (/ 0., 0., 0. /)
DB = (/ 600., 0., 0. /)
DC = (/ 500., 0., 400. /)
! Define starting point
KA = (/ ... |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Icon_and_Unicon | Icon and Unicon | global mlck, nCons, cons
procedure main()
mlck := mutex()
nCons := 0
cons := mutex(set())
while f := open(":12321","na") do {
handle_client(f)
critical mlck: if nCons <= 0 then close(f)
}
end
procedure handle_client(f)
critical mlck: nCons +:= 1
thread {
selec... |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
ar... | #PARI.2FGP | PARI/GP | tanEval(coef, f)={
if (coef <= 1, return(if(coef<1,-tanEval(-coef, f),f)));
my(a=tanEval(coef\2, f), b=tanEval(coef-coef\2, f));
(a + b)/(1 - a*b)
};
tans(xs)={
if (#xs == 1, return(tanEval(xs[1][1], xs[1][2])));
my(a=tans(xs[1..#xs\2]),b=tans(xs[#xs\2+1..#xs]));
(a + b)/(1 - a*b)
};
test(v)={
my(t=tans(v));
if... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #BBC_BASIC | BBC BASIC | charCode = 97
char$ = "a"
PRINT CHR$(charCode) : REM prints a
PRINT ASC(char$) : REM prints 97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Befunge | Befunge | "a". 99*44*+, @ |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #jq | jq | # Create an m x n matrix
def matrix(m; n; init):
if m == 0 then []
elif m == 1 then [range(0; n)] | map(init)
elif m > 0 then
matrix(1; n; init) as $row
| [range(0; m)] | map( $row )
else error("matrix\(m);_;_) invalid")
end ;
# Print a matrix neatly, each cell ideally occupying n spaces,
# ... |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Julia | Julia |
a = [25 15 5; 15 18 0; -5 0 11]
b = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106]
println(a, "\n => \n", chol(a, :L))
println(b, "\n => \n", chol(b, :L))
|
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Kotlin | Kotlin | // Version 1.2.71
val months = listOf(
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
)
class Birthday(val month: Int, val day: Int) {
public override fun toString() = "${months[month - 1]} $day"
public fun monthUniqueIn(bds... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Rust | Rust |
//! We implement this task using Rust's Barriers. Barriers are simply thread synchronization
//! points--if a task waits at a barrier, it will not continue until the number of tasks for which
//! the variable was initialized are also waiting at the barrier, at which point all of them will
//! stop waiting. This can... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Scala | Scala | import java.util.{Random, Scanner}
object CheckpointSync extends App {
val in = new Scanner(System.in)
/*
* Informs that workers started working on the task and
* starts running threads. Prior to proceeding with next
* task syncs using static Worker.checkpoint() method.
*/
private def runTasks(nTa... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Lingo | Lingo | -- list stuff
l = [1, 2]
l.add(3)
l.add(4)
put l
-- [1, 2, 3, 4]
-- property list stuff
pl = [#foo: 1, #bar: 2]
pl[#foobar] = 3
pl["barfoo"] = 4
put pl
-- [#foo: 1, #bar: 2, #foobar: 3, "barfoo": 4] |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Perl | Perl | use ntheory qw/forcomb/;
forcomb { print "@_\n" } 5,3 |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Scala | Scala | if (n == 12) "twelve" else "not twelve"
today match {
case Monday =>
Compute_Starting_Balance;
case Friday =>
Compute_Ending_Balance;
case Tuesday =>
Accumulate_Sales
case _ => {}
} |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Haskell | Haskell | import Control.Monad (zipWithM)
egcd :: Int -> Int -> (Int, Int)
egcd _ 0 = (1, 0)
egcd a b = (t, s - q * t)
where
(s, t) = egcd b r
(q, r) = a `quotRem` b
modInv :: Int -> Int -> Either String Int
modInv a b =
case egcd a b of
(x, y)
| a * x + b * y == 1 -> Right x
| otherwise ->
... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
FUNCTION chowla(BYVAL n AS LONG) AS LONG
REGISTER i AS LONG, j AS LONG
LOCAL r AS LONG
i = 2
DO WHILE i * i <= n
j = n \ i
IF n MOD i = 0 THEN
r += i
IF i <> j THEN
r += j
END IF
END IF
I... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Prolog | Prolog |
chowla(1, 0).
chowla(2, 0).
chowla(N, C) :-
N > 2,
Max is floor(sqrt(N)),
findall(X, (between(2, Max, X), N mod X =:= 0), Xs),
findall(Y, (member(X1, Xs), Y is N div X1, Y \= Max), Ys),
!,
sum_list(Xs, S1),
sum_list(Ys, S2),
C is S1 + S2.
prime_count(Upper, Upper, Count, Count) :-
... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #zkl | zkl | class Church{ // kinda heavy, just an int + fcn churchAdd(ca,cb) would also work
fcn init(N){ var n=N; } // Church Zero is Church(0)
fcn toInt(f,x){ do(n){ x=f(x) } x } // c(3)(f,x) --> f(f(f(x)))
fcn succ{ self(n+1) }
fcn __opAdd(c){ self(n+c.n) }
fcn __opMul(c){ self(n*c.n) }
fcn pow(c) ... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Lingo | Lingo | ----------------------------------------
-- @desc Class "MyClass"
-- @file parent script "MyClass"
----------------------------------------
-- instance variable
property _myvar
-- constructor
on new (me)
me._myvar = 23
return me
end
-- a method
on doubleAndPrint (me)
me._myvar = me._myvar * 2
pu... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Lisaac | Lisaac | Section Header
+ name := SAMPLE;
Section Inherit
- parent : OBJECT := OBJECT;
Section Private
+ variable : INTEGER <- 0;
Section Public
- some_method <- (
variable := 1;
);
- main <- (
+ sample : SAMPLE;
sample := SAMPLE.clone;
sample.some_method;
); |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #OCaml | OCaml |
type point = { x : float; y : float }
let cmpPointX (a : point) (b : point) = compare a.x b.x
let cmpPointY (a : point) (b : point) = compare a.y b.y
let distSqrd (seg : (point * point) option) =
match seg with
| None -> max_float
| Some(line) ->
let a = fst line in
let b = snd line in
... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #TXR | TXR | (let ((funs (mapcar (ret (op * @@1 @@1)) (range 1 10))))
[mapcar call [funs 0..-1]]) |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Wren | Wren | var fs = List.filled(10, null)
for (i in 0...fs.count) {
fs[i] = Fn.new { i * i }
}
for (i in 0...fs.count-1) System.print("Function #%(i): %(fs[i].call())") |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #JavaScript | JavaScript | const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2;
const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1));
const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]];
const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2);
const ... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #Java | Java | public class Zodiac {
final static String animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};
final static String elements[]={"Wood","Fire","Earth","Metal","Water"};
final static String animalChars[]={"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"};
static Stri... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Crystal | Crystal | def check_file(filename : String)
if File.directory?(filename)
puts "#{filename} is a directory"
elsif File.exists?(filename)
puts "#{filename} is a file"
else
puts "#{filename} does not exist"
end
end
check_file("input.txt")
check_file("docs")
check_file("/input.txt")
check_file("/docs") |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #D | D | import std.stdio, std.file, std.path;
void verify(in string name) {
if (name.exists())
writeln("'", name, "' exists");
else
writeln("'", name, "' doesn't exist");
}
void main() {
// check in current working dir
verify("input.txt");
verify("docs");
// check in root
verif... |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a ... | #FreeBASIC | FreeBASIC |
' Chaos game
Const ancho = 320, alto = 240
Dim As Integer x, y, iteracion, vertice
x = Int(Rnd * ancho)
y = Int(Rnd * alto)
Screenres ancho, alto, 8
Cls
For iteracion = 1 To 30000
vertice = Int(Rnd * 3) + 1
Select Case vertice
Case 1
x = x / 2
y = y / 2
vertice = 4 'red
Case 2
... |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Java | Java | import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer implements Runnable
{
private int port = 0;
private List<Client> clients = new ArrayList<Client>();
public ChatServer(int port)
{ this.port = port; }
public void run()
{
try
{
ServerSocket ss = new ServerS... |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
ar... | #Perl | Perl | use Math::BigRat try=>"GMP";
sub taneval {
my($coef,$f) = @_;
$f = Math::BigRat->new($f) unless ref($f);
return 0 if $coef == 0;
return $f if $coef == 1;
return -taneval(-$coef, $f) if $coef < 0;
my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) );
($a+$b)/(1-$a*$b);
}
sub tans {
my ... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #BQN | BQN | FromCharCode ← @⊸+
@⊸+
FromCharCode 97
'a'
FromCharCode 97‿67‿126
"aC~"
FromCharCode⁼ 'a'
97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #Bracmat | Bracmat | ( put
$ ( str
$ ( "\nLatin a
ISO-9959-1: "
asc$a
" = "
chr$97
"
UTF-8: "
utf$a
" = "
chu$97
\n
"Cyrillic а (UTF-8): "
utf$а
" = "
chu$1072
\n
)
)
) |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Kotlin | Kotlin | // version 1.0.6
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i *... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Lua | Lua | -- Cheryl's Birthday in Lua 6/15/2020 db
local function Date(mon,day)
return { mon=mon, day=day, valid=true }
end
local choices = {
Date("May", 15), Date("May", 16), Date("May", 19),
Date("June", 17), Date("June", 18),
Date("July", 14), Date("July", 16),
Date("August", 14), Date("August", 15), Date("Augus... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Tcl | Tcl | package require Tcl 8.5
package require Thread
namespace eval checkpoint {
namespace export {[a-z]*}
namespace ensemble create
variable members {}
variable waiting {}
variable event
# Back-end of join operation
proc Join {id} {
variable members
variable counter
if {$id ni $members} {
... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Lisaac | Lisaac | + vector : ARRAY[INTEGER];
vector := ARRAY[INTEGER].create_with_capacity 32 lower 0;
vector.add_last 1;
vector.add_last 2; |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Perl5i | Perl5i |
use perl5i::2;
# ----------------------------------------
# generate combinations of length $n consisting of characters
# from the sorted set @set, using each character once in a
# combination, with sorted strings in sorted order.
#
# Returns a list of array references, each containing one combination.
#
func combi... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Scheme | Scheme | (if <test> <consequent> <alternate>) |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Icon_and_Unicon | Icon and Unicon | link numbers # for gcd()
procedure main()
write(cr([3,5,7],[2,3,2]) | "No solution!")
write(cr([10,4,9],[11,22,19]) | "No solution!")
end
procedure cr(n,a)
if 1 ~= gcd(n[i := !*n],a[i]) then fail # Not pairwise coprime
(prod := 1, sm := 0)
every prod *:= !n
every p := prod/(ni := n[i := !... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Python | Python | # https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.factor_.divisors
from sympy import divisors
def chowla(n):
return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n
def is_prime(n):
return chowla(n) == 0
def primes_to(n):
return sum(chowla(i) == 0 for i in range(2, n))
def pe... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Logtalk | Logtalk | :- object(metaclass,
instantiates(metaclass)).
:- public(new/2).
new(Instance, Value) :-
self(Class),
create_object(Instance, [instantiates(Class)], [], [state(Value)]).
:- end_object.
:- object(class,
instantiates(metaclass)).
:- public(method/1).
method(Value) :-
... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Lua | Lua | myclass = setmetatable({
__index = function(z,i) return myclass[i] end, --this makes class variables a possibility
setvar = function(z, n) z.var = n end
}, {
__call = function(z,n) return setmetatable({var = n}, myclass) end
})
instance = myclass(3)
print(instance.var) -->3
instance:setvar(6)
print(instance.var... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Oz | Oz | declare
fun {Distance X1#Y1 X2#Y2}
{Sqrt {Pow X2-X1 2.0} + {Pow Y2-Y1 2.0}}
end
%% brute force
fun {BFClosestPair Points=P1|P2|_}
Ps = {List.toTuple unit Points} %% for efficient random access
N = {Width Ps}
MinDist = {NewCell {Distance P1 P2}}
MinPoints = {NewCell P1#P2}
in
fo... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Yabasic | Yabasic |
dim funcs$(10)
sub power2(i)
return i * i
end sub
for i = 1 to 10
funcs$(i) = "power2"
next
for i = 1 to 10
print execute(funcs$(i), i)
next
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #zkl | zkl | (0).pump(10,List,fcn(i){i*i}.fp)[8]() //-->64
list:=(0).pump(10,List,fcn(i){i*i}.fp);
foreach n in (list.len()-1) { list[n]().println() }
list.run(True).println() |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #jq | jq | # circle_centers is defined here as a filter.
# Input should be an array [x1, y1, x2, y2, r] giving the co-ordinates
# of the two points and a radius.
# If there is one solution, the output is the circle center;
# if there are two solutions centered at [x1, y1] and [x2, y2],
# then the output is [x1, y1, x2, y2];
# oth... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #JavaScript | JavaScript | (() => {
"use strict";
// ---------- TRADITIONAL CALENDAR STRINGS -----------
// ats :: Array Int (String, String)
const ats = () =>
// 天干 tiangan – 10 heavenly stems
zip(
chars("甲乙丙丁戊己庚辛壬癸")
)(
words("jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi")
... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #DBL | DBL | ;
; Check file and directory exists for DBL version 4 by Dario B.
;
PROC
;------------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message
CLOSE 1
OPEN (1,O,'TT:')
;The file path can be written as:
... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #DCL | DCL | $ if f$search( "input.txt" ) .eqs. ""
$ then
$ write sys$output "input.txt not found"
$ else
$ write sys$output "input.txt found"
$ endif
$ if f$search( "docs.dir" ) .eqs. ""
$ then
$ write sys$output "directory docs not found"
$ else
$ write sys$output "directory docs found"
$ endif
$ if f$search( "[000000]input.t... |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | offset = 32; //Distance from triangle vertices to edges of window
//triangle vertex coordinates
x1 = room_width / 2;
y1 = offset;
x2 = room_width - offset;
y2 = room_height - offset;
x3 = offset;
y3 = room_height - offset;
//Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step even... |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #JavaScript | JavaScript | const net = require("net");
const EventEmitter = require("events").EventEmitter;
/*******************************************************************************
* ChatServer
*
* Manages connections, users, and chat messages.
******************************************************************************/
class ... |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
ar... | #Phix | Phix | with javascript_semantics
procedure test(atom a)
if -3*PI/4 >= a then ?9/0 end if
if 5*PI/4 <= a then ?9/0 end if
string s = sprint(tan(a))
?s -- or test for "1.0"/"1", but not 1.0
end procedure
test( arctan(1 / 2) + arctan(1 / 3))
test( 2*arctan(1 / 3) + arctan(1 / 7))
test( 4*arctan(... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #C | C | #include <stdio.h>
int main() {
printf("%d\n", 'a'); /* prints "97" */
printf("%c\n", 97); /* prints "a"; we don't have to cast because printf is type agnostic */
return 0;
} |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #C.23 | C# | using System;
namespace RosettaCode.CharacterCode
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int) 'a'); //Prints "97"
Console.WriteLine((char) 97); //Prints "a"
}
}
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Lobster | Lobster | import std
// choleskyLower returns the cholesky decomposition of a symmetric real
// matrix. The matrix must be positive definite but this is not checked
def choleskyLower(order, a) -> [float]:
let l = map(a.length): 0.0
var row, col = 1, 1
var dr = 0 // index of diagonal element at end of row
var d... |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #Maple | Maple | > A := << 25, 15, -5; 15, 18, 0; -5, 0, 11 >>;
[25 15 -5]
[ ]
A := [15 18 0]
[ ]
[-5 0 11]
> B := << 18, 22, 54, 42; 22, 70, 86... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | opts = Tuples[{{"May"}, {15, 16, 19}}]~Join~Tuples[{{"June"}, {17, 18}}]~Join~Tuples[{{"July"}, {14, 16}}]~Join~Tuples[{{"August"}, {14, 15, 17}}];
monthsdelete = Select[GatherBy[opts, Last], Length /* EqualTo[1]][[All, 1, 1]];
opts = DeleteCases[opts, {Alternatives @@ monthsdelete, _}]
removedates = Catenate@Select[Ga... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Nim | Nim | import tables
import sets
import strformat
type Date = tuple[month: string, day: int]
const Dates = [Date ("May", 15), ("May", 16), ("May", 19), ("June", 17), ("June", 18),
("July", 14), ("July", 16), ("August", 14), ("August", 15), ("August", 17)]
const
MonthTable: Table[int, HashSet[string]] ... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Wren | Wren | import "random" for Random
import "scheduler" for Scheduler
import "timer" for Timer
import "/ioutil" for Input
var rgen = Random.new()
var nWorkers = 0
var nTasks = 0
var nFinished = 0
var worker = Fn.new { |id|
var workTime = rgen.int(100, 1000) // 100..999 msec.
System.print("Worker %(id) will work for %... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Logo | Logo | collection = {0, '1'}
print(collection[1]) -- prints 0
collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs
print(collection["foo"]) -- prints 0
print(collection.foo) -- syntactic sugar, also prints 0
collection = {0, '1', ["foo"] = 0, ["bar"] = '1'} |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Phix | Phix | with javascript_semantics
procedure comb(integer pool, needed, done=0, sequence chosen={})
if needed=0 then -- got a full set
?chosen -- (or use a routine_id, result arg, or whatever)
return
end if
if done+needed>pool then return end if -- cannot fulfil
-- get all combinations... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Scilab | Scilab | if condition1 then instructions1
[elseif condition2 then instructions2]
....
[else instructionse]
end
|
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #J | J | crt =: (1 + ] - {:@:[ -: {.@:[ | ])^:_&0@:,: |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Java | Java | import static java.util.Arrays.stream;
public class ChineseRemainderTheorem {
public static int chineseRemainder(int[] n, int[] a) {
int prod = stream(n).reduce(1, (i, j) -> i * j);
int p, sm = 0;
for (int i = 0; i < n.length; i++) {
p = prod / n[i];
sm += a[i... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Racket | Racket | #lang racket
(require racket/fixnum)
(define cache-size 35000000)
(define chowla-cache (make-fxvector cache-size -1))
(define (chowla/uncached n)
(for/sum ((i (sequence-filter (λ (x) (zero? (modulo n x))) (in-range 2 (add1 (quotient n 2)))))) i))
(define (chowla n)
(if (> n cache-size)
(chowla/uncache... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Raku | Raku | sub comma { $^i.flip.comb(3).join(',').flip }
sub schnitzel (\Radda, \radDA = 0) {
Radda.is-prime ?? !Radda !! ?radDA ?? Radda
!! sum flat (2 .. Radda.sqrt.floor).map: -> \RAdda {
my \RADDA = Radda div RAdda;
next if RADDA * RAdda !== Radda;
RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA
... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #M2000_Interpreter | M2000 Interpreter |
Class zz {
module bb {
Superclass A {
unique:
counter
}
Superclass B1 {
unique:
counter
}
Superclass B2 {
unique:
counter
}
... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #MATLAB | MATLAB | function GenericClassInstance = GenericClass(varargin)
if isempty(varargin) %No input arguments
GenericClassInstance.classVariable = 0; %Generates a struct
else
GenericClassInstance.classVariable = varargin{1}; %Generates a struct
end
%Converts th... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #PARI.2FGP | PARI/GP | closestPair(v)={
my(r=norml2(v[1]-v[2]),at=[1,2]);
for(a=1,#v-1,
for(b=a+1,#v,
if(norml2(v[a]-v[b])<r,
at=[a,b];
r=norml2(v[a]-v[b])
)
)
);
[v[at[1]],v[at[2]]]
}; |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #Julia | Julia |
immutable Point{T<:FloatingPoint}
x::T
y::T
end
immutable Circle{T<:FloatingPoint}
c::Point{T}
r::T
end
Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T))
using AffineTransforms
function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T)
cp = Circle{T}[]
r >= 0 || ret... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #Julia | Julia | function chinese(year::Int)
pinyin = Dict(
"甲" => "jiă",
"乙" => "yĭ",
"丙" => "bĭng",
"丁" => "dīng",
"戊" => "wù",
"己" => "jĭ",
"庚" => "gēng",
"辛" => "xīn",
"壬" => "rén",
"癸" => "gŭi",
"子" => "zĭ",
"丑" => "chŏu",
"... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #Delphi | Delphi | program EnsureFileExists;
{$APPTYPE CONSOLE}
uses
SysUtils;
begin
if FileExists('input.txt') then
Writeln('File "input.txt" exists.')
else
Writeln('File "input.txt" does not exist.');
if FileExists('\input.txt') then
Writeln('File "\input.txt" exists.')
else
Writeln('File "\input.txt" ... |
http://rosettacode.org/wiki/Chaos_game | Chaos game | The Chaos Game is a method of generating the attractor of an iterated function system (IFS).
One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.
Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a ... | #GML | GML | offset = 32; //Distance from triangle vertices to edges of window
//triangle vertex coordinates
x1 = room_width / 2;
y1 = offset;
x2 = room_width - offset;
y2 = room_height - offset;
x3 = offset;
y3 = room_height - offset;
//Coords of randomly chosen vertex (set to 0 to start, will automatically be set in step even... |
http://rosettacode.org/wiki/Chat_server | Chat server | Task
Write a server for a minimal text based chat.
People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
| #Julia | Julia |
using HttpServer
using WebSockets
const connections = Dict{Int,WebSocket}()
const usernames = Dict{Int,String}()
function decodeMessage( msg )
String(copy(msg))
end
wsh = WebSocketHandler() do req, client
global connections
@show connections[client.id] = client
println("req is $req")
not... |
http://rosettacode.org/wiki/Check_Machin-like_formulas | Check Machin-like formulas | Machin-like formulas are useful for efficiently computing numerical approximations for
π
{\displaystyle \pi }
Task
Verify the following Machin-like formulas are correct by calculating the value of tan (right hand side) for each equation using exact arithmetic and showing they equal 1:
π
4
=
ar... | #Python | Python | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext = '''\
pi/4 = arctan(1/2) + arctan(1/3)
pi/4 = 2*arctan(1/3) + arctan(1/7)
pi/4 = 4*arctan(1/5) - arctan(1/239)
pi/4 = 5*arctan(1/7) + 2*arctan(3/79)
pi/4 = 5*arctan(29/278) + 7*arctan(3/79)
pi/4 = arctan(1/2) + arcta... |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out... | #C.2B.2B | C++ | #include <iostream>
int main() {
std::cout << (int)'a' << std::endl; // prints "97"
std::cout << (char)97 << std::endl; // prints "a"
return 0;
} |
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.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
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.