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/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #Babel | Babel | { nil { nil? } { "Whew!\n" } { "Something is terribly wrong!\n" } ifte << } |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Ceylon | Ceylon | shared abstract class Cell(character) of alive | dead {
shared Character character;
string => character.string;
shared formal Cell opposite;
}
shared object alive extends Cell('#') {
opposite => dead;
}
shared object dead extends Cell('_') {
opposite => alive;
}
shared Map<Character, Cell> cellsByCharacter = m... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #Comal | Comal |
1000 PRINT "F(X)";" FROM";" TO";" L-Rect";" M-Rect";" R-Rect ";" Trapez";" Simpson"
1010 fromval:=0
1020 toval:=1
1030 PRINT "X^3 ";
1040 PRINT USING "#####": fromval;
1050 PRINT USING "#####": toval;
1060 PRINT USING "###.#########": numint(f1, "L", fr... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #Raku | Raku | use Lingua::EN::Numbers;
use Base::Any;
sub rf (int $base = 10, $batch = Any, &op = &infix:<==>) {
my %batch = batch => $batch if $batch;
flat (1 .. ∞).hyper(|%batch).map: {
my int ($this, $last) = $_, $_ % $base;
my int ($rise, $fall) = 0, 0;
while $this {
my int $rem = $t... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Lua | Lua | local order = 0
local legendreRoots = {}
local legendreWeights = {}
local function legendre(term, z)
if (term == 0) then
return 1
elseif (term == 1) then
return z
else
return ((2 * term - 1) * z * legendre(term - 1, z) - (term - 1) * legendre(term - 2, z)) / term
end
end
lo... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Python | Python | # Object Serialization in Python
# serialization in python is accomplished via the Pickle module.
# Alternatively, one can use the cPickle module if speed is the key,
# everything else in this example remains the same.
import pickle
class Entity:
def __init__(self):
self.name = "Entity"
def printName(self):
p... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Racket | Racket | (require racket/serialize) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #FreeBASIC | FreeBASIC | dim as string lyrics(0 to 7, 0 to 1) = {_
{ "fly", "I don't know why she swallowed a fly - Perhaps she'll die!" },_
{ "spider", "That wriggled and jiggled and tickled inside her!" },_
{ "bird", "How absurd to swallow a bird!" },_
{ "cat", "Imagine that! She swallowed a cat!" },_
{ "dog", "What a hog... |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
... | #Wren | Wren | import "io" for Stdin, Stdout
import "/fmt" for Fmt
import "/str" for Str
var units = [
"tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer"
]
var convs = [
0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668,... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #PicoLisp | PicoLisp | (load "@lib/openGl.l")
(glutInit)
(glutInitWindowSize 400 300)
(glutCreateWindow "Triangle")
(displayPrg
(glClearColor 0.3 0.3 0.3 0.0)
(glClear (| GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT))
(glShadeModel GL_SMOOTH)
(glLoadIdentity)
(glTranslatef -15.0 -15.0 0.0)
(glBegin GL_TRIANGLES)
(glColor3... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Pike | Pike | int main() {
GLUE.init(([
"fullscreen": 0,
"resolution": ({ 640, 480 }),
]));
while (1) {
GL.glViewport(0, 0, 640, 480);
GL.glMatrixMode(GL.GL_PROJECTION);
GL.glLoadIdentity();
GL.glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0);
GL.glMatrixMode(GL.GL_MODELVIEW);
GL.glClearColor(0.3,0.3,0.3,0.0);
... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Maple | Maple |
with(RandomTools[MersenneTwister]);
one_of_n_lines_in_a_file := proc(fn)
local fid, N, n, L, l, line;
fid := fopen(fn,'READ');
if fid<0 then
return;
end if;
N := 0;
n := 1;
while not feof(fid) do
N := N+1;
L := FileTools[Text][ReadLine](fid);
if (N*GenerateFloat() < 1) then
n := N;
line := L... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | chooseLine[file_] := Block[{strm = OpenRead[file], n = 1, rec, selected},
rec = selected = Read[strm];
While[rec =!= EndOfFile,
rec=Read[strm];
n++;
... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #REXX | REXX | sortStrings: procedure expose @. /*the stemmed array is named: @. */
col= 1 /*set some defaults (here and below). */
reverse= 'NO'
order= 'LEXICOGRAPHIC'
arg options /*obtain the options (in uppercase). */
... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Oforth | Oforth | [1,2,0,4,4,0,0,0] [1,2,1,3,2] <= .
1 ok
|
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Ol | Ol |
(define (lexorder a b)
(cond
((null? b) #false)
((null? a) #true)
((< (car a) (car b)) #true)
((> (car a) (car b)) #false)
(else
(lexorder (cdr a) (cdr b)))))
(print (lexorder '(1 2 3) '(1 2 3 4))) ; => true
(print (lexorder '(1 2 4) '(1 2 3))) ; => false
(print (lexorder... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Maple | Maple | lst := StringTools:-Split(Import("http://www.puzzlers.org/pub/wordlists/unixdict.txt"), "\n"):
longest := 0:
words := Array():
i := 1:
for word in lst do
if StringTools:-IsSorted(word) then
len := StringTools:-Length(word):
if len > longest then
longest := len:
words := Array():
words(1) := word:
i := ... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Module[{max,
data = Select[Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"],
OrderedQ[Characters[#]] &]},
max = Max[StringLength /@ data];
Select[data, StringLength[#] == max &]]
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #PureBasic | PureBasic | Procedure IsPalindrome(StringToTest.s)
If StringToTest=ReverseString(StringToTest)
ProcedureReturn 1
Else
ProcedureReturn 0
EndIf
EndProcedure |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #PARI.2FGP | PARI/GP | add(a,b)=if(type(a)==type(b), a+b, if(type(a)=="t_VEC",a+[b,0],b+[a,0]));
sub(a,b)=if(type(a)==type(b), [a[1]-b[1],a[2]+b[2]], if(type(a)=="t_VEC",a-[b,0],[a,0]-b));
mult(a,b)=if(type(a)=="t_VEC", if(type(b)=="t_VEC", [a[1]*b[1], abs(a[1]*b[1])*sqrt(norml2([a[2]/a[1],b[2]/b[1]]))], [b*a[1], abs(b)*a[2]]), [a*b[1], abs(... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Julia | Julia | # io = readstring(STDIN)
io = "what,is,the;meaning,of:life."
i = 0
readbyte!() = io[global i += 1]
writebyte(c) = print(Char(c))
function odd(prev::Function = () -> false)
a = readbyte!()
if !isalpha(a)
prev()
writebyte(a)
return a != '.'
end
# delay action until later, in... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Kotlin | Kotlin | // version 1.1.3
typealias Func = () -> Unit
fun doChar(odd: Boolean, f: Func?): Boolean {
val c = System.`in`.read()
if (c == -1) return false // end of stream reached
val ch = c.toChar()
fun writeOut() {
print(ch)
if (f != null) f()
}
if (!odd) print(ch)
if (ch.isLe... |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #Applesoft_BASIC | Applesoft BASIC | 10 INPUT "GIMME A NUMBER! "; N
20 GOSUB 100"NUMBER NAME
30 PRINT R$
40 END
100 REMNUMBER NAME
110 IF R$ = "" THEN FOR I = 0 TO 10 : READ S$(I), T$(I), U$(I), V$(I) : NEXT
120 IF N = 0 THEN R$ = "ZERO" : RETURN
130 R$ = "" : D = 10 : C = 100 : M = 1E3
140 A = ABS(N)
150 FOR U = 0 TO D
160 H = A - C * INT(A / C)
17... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #BASIC256 | BASIC256 |
print "Dada una lista aleatoria de numeros del 1 al 9,"
print "indica cuantos digitos de la izquierda voltear."
print " El objetivo es obtener los digitos en orden "
print " con el 1 a la izquierda y el 9 a la derecha." + chr(10)
dim nums(10)
dim a(10)
intentos = 0: denuevo = true: colum = 6
#valores iniciales
fo... |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #BASIC | BASIC | TRUE = 1 : FALSE = 0
NULL = TRUE
IF NULL THEN PRINT "NULL"
NULL = FALSE
IF NOT NULL THEN PRINT "NOT NULL" |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #Bracmat | Bracmat |
a:?x*a*?z {assigns 1 to x and to z}
a:?x+a+?z {assigns 0 to x and to z}
a:?x a ?z {assigns "" (or (), which is equivalent) to x and to z}
|
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Clojure | Clojure | (ns one-dimensional-cellular-automata
(:require (clojure.contrib (string :as s))))
(defn next-gen [cells]
(loop [cs cells ncs (s/take 1 cells)]
(let [f3 (s/take 3 cs)]
(if (= 3 (count f3))
(recur (s/drop 1 cs)
(str ncs (if (= 2 (count (filter #(= \# %) f3))) "#" "_")))
(st... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #Common_Lisp | Common Lisp | (defun left-rectangle (f a b n &aux (d (/ (- b a) n)))
(* d (loop for x from a below b by d summing (funcall f x))))
(defun right-rectangle (f a b n &aux (d (/ (- b a) n)))
(* d (loop for x from b above a by d summing (funcall f x))))
(defun midpoint-rectangle (f a b n &aux (d (/ (- b a) n)))
(* d (loop for x... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #REXX | REXX | /*REXX pgm finds and displays N numbers that have an equal number of rises and falls,*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 200 /*Not specified? Then use the default.*/
append= n>0 ... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | gaussLegendreQuadrature[func_, {a_, b_}, degree_: 5] :=
Block[{nodes, x, weights},
nodes = Cases[NSolve[LegendreP[degree, x] == 0, x], _?NumericQ, Infinity];
weights = 2 (1 - nodes^2)/(degree LegendreP[degree - 1, nodes])^2;
(b - a)/2 weights.func[(b - a)/2 nodes + (b + a)/2]]
gaussLegendreQuadrature[Exp, {-3, 3}] |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Raku | Raku | # Reference:
# https://docs.raku.org/language/classtut
# https://github.com/teodozjan/perl-store
use v6;
use PerlStore::FileStore;
class Point {
has Int $.x;
has Int $.y;
}
class Rectangle does FileStore {
has Point $.lower;
has Point $.upper;
method area() returns Int {
($!upper.x ... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Ruby | Ruby | class Being
def initialize(specialty=nil)
@specialty=specialty
end
def to_s
"(object_id = #{object_id})\n"+"(#{self.class}):".ljust(12)+to_s4Being+(@specialty ? "\n"+" "*12+@specialty : "")
end
def to_s4Being
"I am a collection of cooperative molecules with a talent for self-preservation."
end
e... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #Free_Pascal | Free Pascal | (* A mixture of the lyrics found in Wikipedia and the Ada version
in Rosetta Code. It formats the lyrics like the Wikipedia one *)
program OldLady;
uses
SysUtils;
const
MaxLadies = 9; //Number of iterations and array items
Animals: array[1..MaxLadies + 1] of shortstring = ( //Add one for the song's end... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #Frege | Frege | module OldLady where
import Data.List
-- Once means the phrase is only printed in the verse about that animal.
-- Every means the phrase is printed for every verse. It is used for "fly",
-- and could optionally be used for "spider", in the version of the song where
-- "wriggled and jiggled..." is repeated every ve... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #PureBasic | PureBasic |
XIncludeFile "OpenGL.pbi"
pfd.PIXELFORMATDESCRIPTOR
FlatMode = 0 ; Enable Or disable the 'Flat' rendering
WindowWidth = 800 ; The window & GLViewport dimensions
WindowHeight = 600
hWnd = OpenWindow(0, 0, 0, WindowWidth, WindowHeight, "OpenGL Triangle", #PB_Window_SystemMenu)
hdc = GetDC_(hWnd)
pfd\nSize = SizeOf(PIXE... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #MATLAB_.2F_Octave | MATLAB / Octave | function [n,line] = one_of_n_lines_in_a_file(fn)
fid = fopen(fn,'r');
if fid<0, return; end;
N = 0;
n = 1;
while ~feof(fid)
N = N+1;
L = fgetl(fid);
if (N*rand() < 1)
n = N;
line = L;
end;
end
fclose(fid); |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Nim | Nim | import random
randomize()
proc oneOfN(n: int): int =
result = 0
for x in 0 ..< n:
if random(x) == 0:
result = x
proc oneOfNTest(n = 10, trials = 1_000_000): seq[int] =
result = newSeq[int](n)
if n > 0:
for i in 1..trials:
inc result[oneOfN(n)]
echo oneOfNTest() |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Ruby | Ruby | def table_sort(table, ordering=:<=>, column=0, reverse=false)
# ... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Rust | Rust | use std::cmp::Ordering;
struct Table {
rows: Vec<Vec<String>>,
ordering_function: fn(&str, &str) -> Ordering,
ordering_column: usize,
reverse: bool,
}
impl Table {
fn new(rows: Vec<Vec<String>>) -> Table {
Table {
rows: rows,
ordering_column: 0,
revers... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #PARI.2FGP | PARI/GP | lex(u,v)<1 |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Perl | Perl | use strict;
use warnings;
sub orderlists {
my ($firstlist, $secondlist) = @_;
my ($first, $second);
while (@{$firstlist}) {
$first = shift @{$firstlist};
if (@{$secondlist}) {
$second = shift @{$secondlist};
if ($first < $second) {
return 1;
... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #MATLAB_.2F_Octave | MATLAB / Octave | maxlen = 0;
listlen= 0;
fid = fopen('unixdict.txt','r');
while ~feof(fid)
str = fgetl(fid);
if any(diff(abs(str))<0) continue; end;
if length(str)>maxlen,
list = {str};
maxlen = length(str);
elseif length(str)==maxlen,
list{end+1} = str;
end;
end
fclose(fid);
printf('%s\n',list{:}); |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Python | Python | def is_palindrome(s):
return s == s[::-1] |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #Perl | Perl | use utf8;
package ErrVar;
use strict;
# helper function, apply f to pairs (a, b) from listX and listY
sub zip(&$$) {
my ($f, $x, $y) = @_;
my $l = $#$x;
if ($l < $#$y) { $l = $#$y };
my @out;
for (0 .. $l) {
local $a = $x->[$_];
local $b = $y->[$_];
push @out, $f->();
}
\@out
}
use overload
'""' => ... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Lasso | Lasso | define odd_word_processor(str::string) => {
local(
isodd = false,
pos = 1,
invpos = 1,
lastpos = 1
)
while(#str->get(#pos) != '.' && #pos <= #str->size) => {
if(not #str->isAlpha(#pos)) => {
not #isodd ? #isodd = true | #isodd = false
}
if(#isodd) => {
#lastpos = 1
#invpos = 1
while... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Lua | Lua | function reverse()
local ch = io.read(1)
if ch:find("%w") then
local rc = reverse()
io.write(ch)
return rc
end
return ch
end
function forward()
ch = io.read(1)
io.write(ch)
if ch == "." then return false end
if not ch:find("%w") then
ch = reverse()
if ch then io.write(ch) end
i... |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #AutoHotkey | AutoHotkey | Loop { ; TEST LOOP
n =
Random Digits, 1, 36 ; random number with up to 36 digits
Loop %Digits% {
Random Digit, 0, 9 ; can have leading 0s
n .= Digit
}
MsgBox 1, Number Names, % PrettyNumber(n) "`n`n" Spell(n) "`n`n"
... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #Batch_File | Batch File |
::
::Number Reversal Game Task from Rosetta Code Wiki
::Batch File Implementation
::
::Please do not open this from command prompt.
::Directly Open the Batch File to play...
::
@echo off
setlocal enabledelayedexpansion
title Number Reversal Game
:begin
set score=0
::The ascending list of 9 digits
set list=123456... |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #C | C | #include <stdio.h>
int main()
{
char *object = 0;
if (object == NULL) {
puts("object is null");
}
return 0;
} |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #C.23 | C# | if (foo == null)
Console.WriteLine("foo is null"); |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #COBOL | COBOL |
Identification division.
Program-id. rc-1d-cell.
Data division.
Working-storage section.
*> "Constants." ... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #D | D | import std.stdio, std.typecons, std.typetuple;
template integrate(alias method) {
double integrate(F, Float)(in F f, in Float a,
in Float b, in int steps) {
double s = 0.0;
immutable double h = (b - a) / steps;
foreach (i; 0 .. steps)
s += method(... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #Sidef | Sidef | func isok(arr) {
var diffs = arr.map_cons(2, {|a,b| a - b })
diffs.count { .is_pos } == diffs.count { .is_neg }
}
var base = 10
with (200) {|n|
say "First #{n} terms (base #{base}):"
n.by { isok(.digits(base)) && .is_pos }.each_slice(20, {|*a|
say a.map { '%3s' % _ }.join(' ')
})
}
wit... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #Swift | Swift | import Foundation
func equalRisesAndFalls(_ n: Int) -> Bool {
var total = 0
var previousDigit = -1
var m = n
while m > 0 {
let digit = m % 10
m /= 10
if previousDigit > digit {
total += 1
} else if previousDigit >= 0 && previousDigit < digit {
to... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #MATLAB | MATLAB |
%Print the result.
disp(GLGD_int(@(x) exp(x), -3, 3, 5));
%Integration using Gauss-Legendre quad
%Does almost the same as 'integral' in MATLAB
function y=GLGD_int(fun,xmin,xmax,n)
%fun: the intergrand as a function handle
%xmin: lower boundary of integration
%xmax: upper boundary of integration
%n: order of polynom... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Rust | Rust | serde = { version = "1.0.89", features = ["derive"] }
bincode = "1.1.2" |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Tcl | Tcl | package require Tcl 8.6
package require TclOO::serializer 0.1
# These classes are inspired by the Perl example
oo::class create Greeting {
superclass oo::serializable
variable v
constructor {} {
set v "Hello world!"
}
method get {} {
return $v
}
}
oo::class create SubGreeting {... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #Go | Go | package main
import "fmt"
var name, lyric, animals = 0, 1, [][]string{
{"fly", "I don't know why she swallowed a fly. Perhaps she'll die."},
{"spider", "That wiggled and jiggled and tickled inside her."},
{"bird", "How absurd, to swallow a bird."},
{"cat", "Imagine that, she swallowed a cat."},
{"dog", "What a... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Python | Python | #!/usr/bin/env python
#-*- coding: utf-8 -*-
from OpenGL.GL import *
from OpenGL.GLUT import *
def paint():
glClearColor(0.3,0.3,0.3,0.0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glShadeModel(GL_SMOOTH)
glLoadIdentity()
glTranslatef(-15.0, -15.0, 0.0)
glBegin(GL_TRIANGLES)
... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #OCaml | OCaml | let one_of_n n =
let rec aux i r =
if i >= n then r else
if Random.int (i + 1) = 0
then aux (succ i) i
else aux (succ i) r
in
aux 1 0
let test ~n ~trials =
let ar = Array.make n 0 in
for i = 1 to trials do
let d = one_of_n n in
ar.(d) <- succ ar.(d)
done;
Array.iter (Printf... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #PARI.2FGP | PARI/GP | one_of_n(n)={
my(chosen=1);
for(k=2,n,
if(random(k)==0, chosen=k)
);
chosen;
}
v=vector(10); for(i=1,1e6, v[one_of_n(10)]++); v |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Scala | Scala | def sortTable(data: List[List[String]],
ordering: (String, String) => Boolean = (_ < _),
column: Int = 0,
reverse: Boolean = false) = {
val result = data.sortWith((a, b) => ordering(a(column), b(column)))
if (reverse) result.reverse else result
} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Phix | Phix | with javascript_semantics
?{1,2,3}<{1,2,3,4} -- 1 (true under p2js)
?{1,2,3,4}<{1,2,3} -- 0 (false "")
?{1,2,4}<{1,2,3} -- 0 (false "")
?{1,2,3}<{1,2,3} -- 0 (false "")
?{1,2,3}<{1,2,4} -- 1 (true "")
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Nanoquery | Nanoquery | import Nanoquery.IO
def is_ordered(word)
word = str(word)
if len(word) < 2
return true
end
for i in range(1, len(word) - 1)
if str(word[i]) < str(word[i - 1])
return false
end
end
return true
end
longest = 0
words = {}
for word in new(File, "unixdict.t... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
unixdict = 'unixdict.txt'
do
wmax = Integer.MIN_VALUE
dwords = ArrayList()
inrdr = BufferedReader(FileReader(File(unixdict)))
loop label ln while inrdr.ready
dword = Rexx(inrdr.readLine).strip
if isOrdered(dword) then d... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #Quackery | Quackery | [ dup reverse = ] is palindromic ( [ --> b )
[ [] swap witheach
[ upper dup
dup lower = iff
drop else join ]
palindromic ] is inexactpalindrome ( $ --> b ) |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #Phix | Phix | with javascript_semantics
enum VALUE, DELTA
type imprecise(object imp)
return sequence(imp) and atom(imp[VALUE]) and atom(imp[DELTA])
end type
function sqr(atom a)
return a*a
end function
function imprecise_add(imprecise a, b)
atom delta = sqrt(sqr(a[DELTA]) + sqr(b[DELTA]))
imprecise ret = {a[VA... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
global out$
document out$
Function PrepareStream$ (buf$) {
\\ get a temporary file
if buf$="" then {
class ref {
f
class:
module ref (.f) { }
}
... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Nim | Nim | import unicode
type Proc = proc(): bool {.closure.}
var nothing: Proc = proc(): bool {.closure.} = false
proc odd(prev = nothing): bool =
let a = stdin.readChar()
if not isAlpha(Rune(ord(a))):
discard prev()
stdout.write(a)
return a != '.'
# delay action until later, in the shape of a closure
... |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #AWK | AWK |
# syntax: GAWK -f NUMBER_NAMES.AWK
BEGIN {
init_numtowords()
n = split("-10 0 .1 8 100 123 1001 99999 100000 9123456789 111000000111",arr," ")
for (i=1; i<=n; i++) {
printf("%s = %s\n",arr[i],numtowords(arr[i]))
}
exit(0)
}
# source: The AWK Programming Language, page 75
function numtowords(... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #BBC_BASIC | BBC BASIC | DIM list%(8), done%(8), test%(8)
list%() = 1, 2, 3, 4, 5, 6, 7, 8, 9
done%() = list%()
REM Shuffle:
REPEAT
FOR i% = 9 TO 2 STEP -1
SWAP list%(i%-1), list%(RND(i%)-1)
NEXT
test%() = list%() - done%()
UNTIL MOD(test%()) <> 0
REM Run the game:... |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #C.2B.2B | C++ | #include <iostream>
#include <cstdlib>
if (object == 0) {
std::cout << "object is null";
} |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #Chapel | Chapel | class C { };
var c:C; // is nil
writeln(if c == nil then "nil" else "something"); |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #Common_Lisp | Common Lisp | (defun value (x)
(assert (> (length x) 1))
(coerce x 'simple-bit-vector))
(defun count-neighbors-and-self (value i)
(flet ((ref (i)
(if (array-in-bounds-p value i)
(bit value i)
0)))
(declare (inline ref))
(+ (ref (1- i))
(ref i)
(ref (1+ i)))))
(... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #Delphi | Delphi | program Numerical_integration;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TFx = TFunc<Double, Double>;
TMethod = TFunc<TFx, Double, Double, Double>;
function RectLeft(f: TFx; x, h: Double): Double;
begin
RectLeft := f(x);
end;
function RectMid(f: TFx; x, h: Double): Double;
begin
RectMid := f(x... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #Wren | Wren | import "/fmt" for Fmt
var risesEqualsFalls = Fn.new { |n|
if (n < 10) return true
var rises = 0
var falls = 0
var prev = -1
while (n > 0) {
var d = n%10
if (prev >= 0) {
if (d < prev) {
rises = rises + 1
} else if (d > prev) {
... |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that ... | #XPL0 | XPL0 | func RiseFall(N); \Return 'true' if N has equal rises and falls
int N, R, F, D, D0;
[R:= 0; F:= 0;
N:= N/10;
D0:= rem(0);
while N do
[N:= N/10;
D:= rem(0);
if D > D0 then R:= R+1;
if D < D0 then F:= F+1;
D0:= D;
];
return R = F;
];
int N, Cnt;
[N:= 1;
Cnt:= 0;
loop [if RiseFall(N) t... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Maxima | Maxima | gauss_coeff(n) := block([p, q, v, w],
p: expand(legendre_p(n, x)),
q: expand(n/2*diff(p, x)*legendre_p(n - 1, x)),
v: map(rhs, bfallroots(p)),
w: map(lambda([z], 1/subst([x = z], q)), v),
[map(bfloat, v), map(bfloat, w)])$
gauss_int(f, a, b, n) := block([u, x, w, c, h],
u: gauss_coeff(n),
x: u[1]... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #Wren | Wren | import "/json" for JSON
import "io" for File, FileFlags
class Entity {
construct new(name) {
_name = name
}
name { _name }
// JSON representation
toString { "{\"name\": \"%(_name)\"}" }
// mimics the JSON output
print() { System.print(this.toString.replace("\"", "")) }
... |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to st... | #Haskell | Haskell | import Data.List (tails)
animals :: [String]
animals =
[ "fly.\nI don't know why she swallowed a fly.\nPerhaps she'll die.\n"
, "spider.\nThat wiggled and jiggled and tickled inside her."
, "bird.\t\nHow absurd, to swallow a bird."
, "cat.\t\nImagine that. She swallowed a cat."
, "dog.\t\nWhat a hog to swal... |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #QB64 | QB64 |
'Task
'Display a smooth shaded triangle with OpenGL.
Screen _NewImage(600, 600, 32)
Dim Shared glInit As Integer
glInput = 0
Do While InKey$ = "": Loop
End
Sub _GL ()
If glInit = 0 Then
_glViewport 1, 1, 600, 600
_glClearColor 0, 0, 0, 1
glInit = -1
End If
_glClear _GL_COLOR_BU... |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Pascal | Pascal | Program OneOfNLines (Output);
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
function one_of_n(n: longint): longint;
var
i: longint;
begin
one_of_n := 1;
for i := 2 to n do
if random < 1.0 / i then
one_of_n := i;
end;
function sum(a: array of longint): longint;
var
i: integer;
begin
R... |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Sidef | Sidef | func table_sort(table, ordering: '<=>', column: 0, reverse: false) {
if (reverse) {
table.sort {|a,b| b[column].$ordering(a[column])}
} else {
table.sort {|a,b| a[column].$ordering(b[column])}
}
}
# Quick example:
var table = [
["Ottowa", "Canada"],
["Washington", "USA"],
["Mexico City", "Mexico"]... |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Phixmonti | Phixmonti | include Utilitys.pmt
def ? print nl enddef
( 1 2 3 ) ( 1 2 3 4 ) < ?
( 1 2 3 4 ) ( 1 2 3 ) < ?
( 1 2 4 ) ( 1 2 3 ) < ?
( 1 2 3 ) ( 1 2 3 ) < ?
( 1 2 3 ) ( 1 2 4 ) < ? |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
She... | #Picat | Picat | go =>
Tests = [
[[1,2,3], [1,2,3]],
[[1,2,3], [1,2,3,4]],
[[1,2,2], [1,2,3]],
[[1,2,4], [1,2,3]],
[1..10 , 1..8],
[[] , []],
[[] , [1]],
[[1] , [] ],
[[-1,2,3,6,5],[-1,2,3,5,6]],
[[-1,2,3,-5,6],[-1,2,3,-6,5]]
],
foreach([L1,L2] in Tests)
printf("%... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Nim | Nim | import strutils
const DictFile = "unixdict.txt"
func isSorted(s: string): bool =
var last = char.low
for c in s:
if c < last: return false
last = c
result = true
var
mx = 0
words: seq[string]
for word in DictFile.lines:
if word.len >= mx and word.isSorted:
if word.len > mx:
words.s... |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #OCaml | OCaml | let input_line_opt ic =
try Some(input_line ic)
with End_of_file -> None
(* load each line in a list *)
let read_lines ic =
let rec aux acc =
match input_line_opt ic with
| Some line -> aux (line :: acc)
| None -> (List.rev acc)
in
aux []
let char_list_of_string str =
let lst = ref [] in
S... |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which ... | #R | R | palindro <- function(p) {
if ( nchar(p) == 1 ) {
return(TRUE)
} else if ( nchar(p) == 2 ) {
return(substr(p,1,1) == substr(p,2,2))
} else {
if ( substr(p,1,1) == substr(p, nchar(p), nchar(p)) ) {
return(palindro(substr(p, 2, nchar(p)-1)))
} else {
return(FALSE)
}
}
} |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #PicoLisp | PicoLisp | (scl 12)
(load "@lib/math.l")
# Overload arithmetic operators +, -, *, / and **
(redef + @
(let R (next)
(while (args)
(let N (next)
(setq R
(if2 (atom R) (atom N)
(+ R N) # c + c
(cons (+ R (car N)) (cdr N)) # c +... |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then... | #Python | Python | from collections import namedtuple
import math
class I(namedtuple('Imprecise', 'value, delta')):
'Imprecise type: I(value=0.0, delta=0.0)'
__slots__ = ()
def __new__(_cls, value=0.0, delta=0.0):
'Defaults to 0.0 ± delta'
return super().__new__(_cls, float(value), abs(float(delta)))
... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #OCaml | OCaml | let is_alpha c =
c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z'
let rec odd () =
let c = input_char stdin in
if is_alpha c
then (let e = odd () in print_char c; e)
else (c)
let rec even () =
let c = input_char stdin in
if is_alpha c
then (print_char c; even ())
else print_char c
let rev_odd_word... |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will... | #Ol | Ol |
(define (odd_word_problem words)
(letrec ((odd (lambda (s out)
(let loop ((s s) (l '()))
(cond
((null? s)
out)
((pair? s)
(if (<= #\a (car s) #\z)
(loop (cdr s) (con... |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negat... | #BASIC | BASIC | DECLARE FUNCTION int2Text$ (number AS LONG)
'small
DATA "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"
DATA "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
'tens
DATA "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty"... |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversa... | #Brat | Brat | sorted = 1.to 9
length = sorted.length
numbers = sorted.shuffle
#Make certain numbers are shuffled
true? numbers == sorted
{ while { sorted == numbers.shuffle! } }
turns = 0
while { numbers != sorted } {
print "#{numbers} - How many to reverse? "
num = g.to_i
numbers = numbers[0, num - 1].reverse + numbe... |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #Clojure | Clojure | (let [x nil]
(println "Object is" (if (nil? x) "nil" "not nil"))) |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #COBOL | COBOL | identification division.
program-id. null-objects.
remarks. test with cobc -x -j null-objects.cob
data division.
working-storage section.
01 thing-not-thing usage pointer.
*> call a subprogram
*> with one null pointer
*> an omitted parameter
... |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the follow... | #D | D | void main() {
import std.stdio, std.algorithm;
enum nGenerations = 10;
enum initial = "0011101101010101001000";
enum table = "00010110";
char[initial.length + 2] A = '0', B = '0';
A[1 .. $-1] = initial;
foreach (immutable _; 0 .. nGenerations) {
foreach (immutable i; 1 .. A.length - 1) {
... |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume t... | #E | E | pragma.enable("accumulator")
def leftRect(f, x, h) {
return f(x)
}
def midRect(f, x, h) {
return f(x + h/2)
}
def rightRect(f, x, h) {
return f(x + h)
}
def trapezium(f, x, h) {
return (f(x) + f(x+h)) / 2
}
def simpson(f, x, h) {
return (f(x) + 4 * f(x + h / 2) + f(x+h)) / 6
}
def integrate(f, a, ... |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle ... | #Nim | Nim |
import math, strformat
proc legendreIn(x: float, n: int): float =
template prev1(idx: int; pn1: float): float =
(2*idx - 1).float * x * pn1
template prev2(idx: int; pn2: float): float =
(idx-1).float * pn2
if n == 0:
return 1.0
elif n == 1:
return x
else:
var
p1 = float x
... |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o... | #zkl | zkl | class [static] ARootClass{ // A top level class, no instances
class A{ self.println(" constructor"); } // a regular class
class B(A){ // ditto
var x;
fcn init(x=123){ self.x=x }
fcn toString{ "x is "+x }
}
}
ARootClass.B(456).println(); // create an instance
// prints:
Class(A) constr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.