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/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 ...
#Fortran
Fortran
! Works with gfortran but needs the option ! -assume realloc_lhs ! when compiled with Intel Fortran.   program gauss implicit none integer, parameter :: p = 16 ! quadruple precision integer :: n = 10, k real(kind=p), allocatable :: r(:,:) real(kind=p) :: z, a, b, exact do n = 1,20 a ...
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...
#Julia
Julia
  abstract type Hello end   struct HelloWorld <: Hello name::String HelloWorld(s) = new(s) end   struct HelloTime <: Hello name::String tnew::DateTime HelloTime(s) = new(s, now()) end   sayhello(hlo) = println("Hello to this world, $(hlo.name)!")   sayhello(hlo::HelloTime) = println("It is now $(now...
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...
#Kotlin
Kotlin
// version 1.2.0   import java.io.*   open class Entity(val name: String = "Entity"): Serializable { override fun toString() = name   companion object { val serialVersionUID = 3504465751164822571L } }   class Person(name: String = "Brian"): Entity(name), Serializable { companion object { ...
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...
#C.2B.2B
C++
#include <iostream>   const char *CREATURES[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; const char *COMMENTS[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine tha...
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: ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[units, ConvertRussianQuantities] units = {"RussianVershoks", "RussianArshins", "RussianSazhens", "RussianVerstas", "Centimeters", "Meters", "Kilometers"}; ConvertRussianQuantities[q_Quantity] := UnitConvert[q, #] & /@ Select[units, QuantityUnit[q] != # &] ConvertRussianQuantities[Quantity[1, "Vershoks"]] Conve...
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: ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П7 1 0 0 * П8 1 ВП 5 / П9 ИП7 1 0 6 7 / П0 5 0 0 * ПC 3 * ПA 1 6 * ПB С/П ПB 1 6 / ПA 3 / ПC 5 0 0 / П0 1 0 6 7 / БП 00
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.
#Lingo
Lingo
global gOpenGL -- RavOpenGL xtra instance global GL -- OpenGL constants   on startMovie -- Load the OpenGL script xtra gOpenGL = xtra("RavOpenGL").new()   -- Load GL DLL gOpenGL.RavLoadGL("", "")   -- Function omitted in demo code: loads OpenGL constants into namespace GL loadGLConstants() ...
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.
#Lua
Lua
local gl = require "luagl" local iup = require "iuplua" require "iupluagl"   local function paint() gl.ClearColor(0.3,0.3,0.3,0.0) gl.Clear"COLOR_BUFFER_BIT,DEPTH_BUFFER_BIT"   gl.ShadeModel"SMOOTH"   gl.LoadIdentity() gl.Translate(-15.0, -15.0, 0.0)   gl.Begin"TRIANGLES" gl.Color(1.0, 0.0, 0.0) gl.Vert...
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...
#Fortran
Fortran
  !> read lines one at a time and randomly choose one !! using a Reservoir Sampling algorithm: !! http://www.rosettacode.org/wiki/One_of_n_lines_in_a_file program reservoir_sample use, intrinsic :: iso_fortran_env, only : dp=>real64 implicit none character(len=256)  :: line integer :: lun, n, i, count(10)...
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
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 Shell Sort ...
#zkl
zkl
fcn disOrder(sm,sn){ M:=sm.split(" "); N:=sn.split(" "); nc:=Walker.cycle(Utils.Helpers.listUnique(N)); dn:=Dictionary(); N.pump(Void,'wrap(w){ dn[w] = dn.find(w,0) + 1; }); M.pump(String,'wrap(w){ if (Void==(n:=dn.find(w))) return(w); // not replaced if (n) { dn[w]=n-1; nc.next(); } // swaps l...
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 ...
#Objective-C
Objective-C
typedef enum { kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } SortOrder;   @interface MyArray : NSObject {} // . . . @end   @implementation MyArray   - (void)sort { [self sortWithOrdering:kOrdLex onColumn:0 reversed:NO]; }   - (void)sortWithOrdering:(SortOrder)ord { [self sortWithOrdering:ord onColumn: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...
#Joy
Joy
  DEFINE order == [equal] [false] [[[[size] dip size <=] [[<=] mapr2 true [and] fold]] [i] map i and] ifte.  
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...
#jq
jq
  [1,2,3] < [1,2,3,4] # => true [1,2,3] < [1,2,4] # => true [1,2,3] < [1,2,3] # => false
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...
#JavaScript
JavaScript
var fs = require('fs'), print = require('sys').print; fs.readFile('./unixdict.txt', 'ascii', function (err, data) { var is_ordered = function(word){return word.split('').sort().join('') === word;}, ordered_words = data.split('\n').filter(is_ordered).sort(function(a, b){return a.length - b.length}).reverse()...
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 ...
#PL.2FM
PL/M
100H:   /* CHECK EXACT PALINDROME ASSUMING $-TERMINATED STRING */ PALINDROME: PROCEDURE(PTR) BYTE; DECLARE (PTR, FRONT, BACK) ADDRESS, STR BASED PTR BYTE;   /* FIND END */ FRONT, BACK = 0; DO WHILE STR(BACK) <> '$'; BACK = BACK + 1; END; BACK = BACK - 1;   /* CHECK MATCH */ DO WH...
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...
#Factor
Factor
USING: accessors arrays fry kernel locals math math.functions multi-methods parser prettyprint prettyprint.custom sequences ; RENAME: GENERIC: multi-methods => MM-GENERIC: FROM: syntax => M: ; IN: imprecise   TUPLE: imprecise { value float read-only } { sigma float read-only } ;   C: <imprecise> imprecise   : >...
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...
#Fortran
Fortran
PROGRAM CALCULATE !A distance, with error propagation. REAL X1, Y1, X2, Y2 !The co-ordinates. REAL X1E,Y1E,X2E,Y2E !Their standard deviation. DATA X1, Y1 ,X2, Y2 /100., 50., 200.,100./ !Specified DATA X1E,Y1E,X2E,Y2E/ 1.1, 1.2, 2.2, 2.3/ !Values. REAL DX,DY,D2,D,DXE,DYE,E !Assistan...
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...
#F.23
F#
open System open System.Text.RegularExpressions   let mutable Inp = Console.In   let Out c = printf "%c" c; (if c = '.' then Environment.Exit 0)   let In() = Inp.Read() |> Convert.ToChar   let (|WordCharacter|OtherCharacter|) c = if Regex.IsMatch(c.ToString(),"[a-zA-Z]") then WordCharacter else ...
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...
#Ada
Ada
  with Ada.Text_Io; use Ada.Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Ada.Numerics.Discrete_Random;   procedure NumberReverse is   subtype RandRange is Integer range 1..9; type NumArrayType is array (Integer range 1..9) of Integer;   package RandNumbers is new Ada.Numerics.Discrete_Rando...
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...
#Action.21
Action!
TYPE Object=[ BYTE byteData INT intData CARD cardData]   PROC IsNull(Object POINTER ptr) IF ptr=0 THEN PrintE("Object is null") ELSE PrintE("Object is not null") FI RETURN   PROC Main() Object a Object POINTER ptr1=a,ptr2=0   IsNull(ptr1) IsNull(ptr2) RETURN
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...
#ActionScript
ActionScript
if (object == null) trace("object 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...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::THE MAIN THING call :one-dca __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__ pause>nul exit /b ::/THE MAIN THING ::THE PROCESSOR :one-dca echo.&set numchars=0&set proc=%1 ::COUNT THE NUMBER OF CHARS set bef=%proc:_=_,% set bef=%bef:#=#,% set bef=%bef:~0,-1% fo...
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...
#BASIC
BASIC
FUNCTION leftRect(a, b, n) h = (b - a) / n sum = 0 FOR x = a TO b - h STEP h sum = sum + h * (f(x)) NEXT x leftRect = sum END FUNCTION   FUNCTION rightRect(a, b, n) h = (b - a) / n sum = 0 FOR x = a + h TO b STEP h sum = sum + h * (f(x)) NEXT x rightRect...
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   ...
#Cowgol
Cowgol
include "cowgol.coh";   # return the change in height of a number sub height(n: uint32): (h: int8) is h := 0; var dgt := (n % 10) as uint8; var prev: uint8; n := n / 10;   while n > 0 loop prev := dgt; dgt := (n % 10) as uint8; n := n / 10; if prev < dgt then ...
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   ...
#F.23
F#
  // A296712. Nigel Galloway: October 9th., 2020 let fN g=let rec fN Ψ n g=match n,Ψ with (0,0)->true |(0,_)->false |_->let i=n%10 in fN (Ψ + (compare i g)) (n/10) i in fN 0 g (g%10) let A296712=seq{1..2147483647}|>Seq.filter fN A296712|>Seq.take 200|>Seq.iter(printf "%d "); printfn"\n" [999999;9999999;99999999]|>List....
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   ...
#Factor
Factor
USING: grouping io kernel lists lists.lazy math math.extras prettyprint tools.memory.private ;   : rises-and-falls-equal? ( n -- ? ) 0 swap 10 /mod swap [ 10 /mod rot over - sgn rotd + spin ] until-zero drop 0 = ;   : OEIS:A296712 ( -- list ) 1 lfrom [ rises-and-falls-equal? ] lfilter ;   ! Task "The first ...
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 ...
#Go
Go
package main   import ( "fmt" "math" )   // cFunc for continuous function. A type definition for convenience. type cFunc func(float64) float64   func main() { fmt.Println("integral:", glq(math.Exp, -3, 3, 5)) }   // glq integrates f from a to b by Guass-Legendre quadrature using n nodes. // For the task, i...
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...
#Neko
Neko
/* Object serialization, in Neko */   var file_open = $loader.loadprim("std@file_open", 2) var file_write = $loader.loadprim("std@file_write", 4) var file_read = $loader.loadprim("std@file_read", 4) var file_close = $loader.loadprim("std@file_close", 1)   var serialize = $loader.loadprim("std@serialize", 1) var unseria...
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...
#Nim
Nim
import marshal, streams   type Base = object of RootObj name: string Descendant = object of Base proc newBase(): Base = Base(name: "base") proc newDescendant(): Descendant = Descendant(name: "descend") proc print(obj: Base) = echo(obj.name)   var base = newBase() descendant = newDescendant() print(base) p...
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...
#CLU
CLU
old_lady = cluster is swallow rep = null   own animals: array[string] := array[string]$[ "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" ]   own lines: array[string] := array[string]$[ "I don't know why she swallowed that fly.\nPerhaps she'll die.\n", "That ...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. OLD-LADY.   DATA DIVISION. WORKING-STORAGE SECTION.   01 LYRICS. 03 THERE-WAS PIC X(38) VALUE "There was an old lady who swallowed a ". 03 SHE-SWALLOWED PIC X(18) VALUE "She swallowed the ". ...
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: ...
#Nim
Nim
import os, strutils, sequtils, tables   const Unit2Mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "t...
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: ...
#Perl
Perl
sub convert { my($magnitude, $unit) = @_; my %factor = ( tochka => 0.000254, liniya => 0.00254, diuym => 0.0254, vershok => 0.04445, piad => 0.1778, fut => 0.3048, arshin => 0.7112, sazhen => 2.1336, 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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Style[Graphics3D[{Polygon[{{-1, 0, 0}, {1, 0, 0}, {0, Sqrt[3], 0.5}}, VertexColors -> {Red, Green, Blue}]}, Boxed -> False], RenderingOptions -> {"3DRenderingEngine" -> "OpenGL"}]
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.
#MAXScript
MAXScript
newMesh = mesh numVerts:3 numFaces:1 setMesh newMesh vertices:#([-100, -100, 0], [100, -100, 0], [-100, 100, 0]) faces:#([1, 2, 3]) defaultVCFaces newMesh setVertColor newMesh 1 red setVertColor newMesh 2 green setVertColor newMesh 3 blue setCVertMode newMesh true update newMesh viewport.setType #view_top max tool maxi...
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...
#FreeBASIC
FreeBASIC
Declare Function one_of_n (n As Long) As Long   Dim As Long L0, c, elegido(1 To 10)   Function one_of_n (n As Long) As Long   'asume que la primera línea es 1 Dim As Long L1, opcion For L1 = 1 To n If Int(Rnd * L1) = 0 Then opcion = L1 Next L1 one_of_n = opcion End Function   Randomize Timer...
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 ...
#OCaml
OCaml
let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table = let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in List.sort cmp table
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...
#Julia
Julia
function islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real}) for (x, y) in zip(a, b) if x == y continue end return x < y end return length(a) < length(b) end   using Primes, Combinatorics tests = [[1, 2, 3], primes(10), 0:2:6, [-Inf, 0.0, Inf], [π, e, φ, catalan], [2015, 5], [-sqrt...
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...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   ( 1 2 3 ) ( 1 2 3 4 ) less ? ( 1 2 3 4 ) ( 1 2 3 ) less ? ( 1 2 4 ) ( 1 2 3 ) less ? ( 1 2 3 ) ( 1 2 3 ) less ? ( 1 2 3 ) ( 1 2 4 ) less ?   "End " input
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...
#jq
jq
def is_sorted: if length <= 1 then true else .[0] <= .[1] and (.[1:] | is_sorted) end;   def longest_ordered_words: # avoid string manipulation: def is_ordered: explode | is_sorted; map(select(is_ordered)) | (map(length)|max) as $max | map( select(length == $max) );     split("\n") | longest_ordered_wo...
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 ...
#Plain_English
Plain English
To decide if a string is palindromic: Slap a substring on the string. Loop. If the substring's first is greater than the substring's last, say yes. If the substring's first's target is not the substring's last's target, say no. Add 1 to the substring's first. Subtract 1 from the substring's last. Repeat.
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...
#FreeBASIC
FreeBASIC
'---------------------- ' definition of a "measurement" type with value and uncartainty ' and operators that can operate on them '---------------------   #macro p2(x) (x)*(x) #endmacro   type meas vlu as double unc as double end type   operator + ( a as meas, b as meas ) as meas dim ret as meas ret....
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...
#Factor
Factor
USING: continuations kernel io io.streams.string locals unicode.categories ; IN: rosetta.odd-word   <PRIVATE ! Save current continuation. : savecc ( -- continuation/f ) [ ] callcc1 ; inline   ! Jump back to continuation, where savecc will return f. : jump-back ( continuation -- ) f swap continue-with ; inline P...
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...
#FALSE
FALSE
[$$$$'.=\',=|\';=|\':=|~[^s;!\,]?]s: {recursive reading} [s;!$'.=~[,^f;!]?]r: {reverse words} [[$$$$'.=\',=|\';=|\':=|~][,^]#$'.=~[,^r;!]?]f: {forward words} ^f;!, {start}
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...
#APL
APL
∇numrev;list;in;swaps list←{9?9}⍣{⍺≢⍳9}⊢⍬ swaps←0 read: swaps+←1 in←{⍞←⍵⋄(≢⍵)↓⍞}(⍕list),': swap how many? ' list←⌽@(⍳⍎in)⊢list →(list≢⍳9)/read ⎕←(⍕list),': Congratulations!' ⎕←'Swaps:',swaps ∇
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...
#Ada
Ada
with Ada.Text_Io;   if Object = null then Ada.Text_Io.Put_line("object is null"); end if;
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...
#ALGOL_68
ALGOL 68
REF STRING no result = NIL; STRING result := "";   IF no result :=: NIL THEN print(("no result :=: NIL", new line)) FI; IF result :/=: NIL THEN print(("result :/=: NIL", new line)) FI;   IF no result IS NIL THEN print(("no result IS NIL", new line)) FI; IF result ISNT NIL THEN print(("result ISNT NIL", new line)) FI;  ...
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...
#BBC_BASIC
BBC BASIC
DIM rule$(7) rule$() = "0", "0", "0", "1", "0", "1", "1", "0"   now$ = "01110110101010100100"   FOR generation% = 0 TO 9 PRINT "Generation " ; generation% ":", now$ next$ = "" FOR cell% = 1 TO LEN(now$) next$ += rule$(EVAL("%"+MID$("0"+now$+"0", cell%, 3))) ...
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...
#BBC_BASIC
BBC BASIC
*FLOAT64 @% = 12 : REM Column width   PRINT "Function Range L-Rect R-Rect M-Rect Trapeze Simpson" FOR func% = 1 TO 4 READ x$, l, h, s% PRINT x$, ; l " - " ; h, FNlrect(x$, l, h, s%) FNrrect(x$, l, h, s%) ; PRINT FNmrect(x$, l, h, s%) FNtrap...
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   ...
#Forth
Forth
: in-seq? ( n -- is N in the sequence? ) 0 swap \ height 10 /mod \ digit and rest of number begin dup while \ as long as the number isn't zero... 10 /mod \ get next digit and quotient -rot swap \ retrieve previous digit over - sgn \ see if higher, lower o...
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   ...
#Fortran
Fortran
PROGRAM A296712 INTEGER IDX, NUM, I * Index and number start out at zero IDX = 0 NUM = 0 * Find and write the first 200 numbers WRITE (*,'(A)') 'The first 200 numbers are: ' DO 100 I = 1, 200 CALL NEXT NUM(IDX, NUM) WRI...
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 ...
#Haskell
Haskell
gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ] where d = (b - a)/2 m = (b + a)/2 w x = 2/(1-x^2)/(legendreP' n x)^2 roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n] x0 i = cos (pi*(i-1/4)/(n+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...
#Objeck
Objeck
  bundle Default { class Thingy { @id : Int;   New(id : Int) { @id := id; }   method : public : Print() ~ Nil { @id->PrintLine(); } }   class Person from Thingy { @name : String;   New(id : Int, name : String) { Parent(id); @name := name; }   method : pu...
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...
#Commodore_BASIC
Commodore BASIC
  1 rem rosetta code 2 rem old lady who swallowed a fly 5 print chr$(147);chr$(14) 10 dim a$(10),ex$(10),mu$(8,3):a=1 15 for i=1 to 8:read a$(i),ex$(i):next i 20 for c=1 to 8 30 print chr$(147):print " Old Lady Who Swallowed A Fly ":print 40 print "I know an old lady who swallowed" 45 print " a ";a$(c):g...
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: ...
#Phix
Phix
with javascript_semantics constant units = {{"-- metric ---",0}, {"kilometer",1000}, {"km","kilometer"}, {"meter",1}, {"m","meter"}, {"centimeter",0.01}, {"cm","centimeter"}, {" old russian ",0...
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.
#Mercury
Mercury
:- module opengl. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module list, glut, glut.callback, glut.window, mogl.   main(!IO) :- glut.init_window_size(640, 480, !IO), glut.window.create("Triangle", !IO), glut.callback.display_func(opengl.paint, !IO)...
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.
#Nim
Nim
import opengl, opengl/glut   proc paint() {.cdecl.} = glClearColor(0.3,0.3,0.3,0.0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)   glShadeModel(GL_SMOOTH)   glLoadIdentity() glTranslatef(-15.0, -15.0, 0.0)   glBegin(GL_TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex2f(0.0, 0.0) glColor3f(0.0, 1.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...
#Go
Go
package main   import ( "bufio" "fmt" "io" "math/rand" "time" )   // choseLineRandomly implements the method described in the task. // input is a an io.Reader, which could be an os.File, for example. // Or, to implement a simulation, it could be anything else that implements // io.Reader. The metho...
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 ...
#Oz
Oz
declare class Table attr rows   meth init(Rows) rows := Rows end   meth sort(ordering:O<=Lexicographic column:C<=1 reverse:R<=false) fun {Predicate Row1 Row2} Res = {O {Nth Row1 C} {Nth Row2 C}} in if R then {Not Res} else Res end end...
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...
#Kotlin
Kotlin
// version 1.0.6   operator fun <T> List<T>.compareTo(other: List<T>): Int where T: Comparable<T>, T: Number { for (i in 0 until this.size) { if (other.size == i) return 1 when { this[i] < other[i] -> return -1 this[i] > other[i] -> return 1 } } return if ...
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...
#Julia
Julia
issorted("abc") # true
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 ...
#Pointless
Pointless
isPalindrome(chars) = chars == reverse(chars)
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...
#Go
Go
package main   import ( "fmt" "math" )   // "uncertain number type" // a little optimization is to represent the error term with its square. // this saves some taking of square roots in various places. type unc struct { n float64 // the number s float64 // *square* of one sigma error term }   // constru...
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...
#Forth
Forth
: word? dup [char] . <> over bl <> and ; : ?quit dup [char] . = if emit quit then ; : eatbl begin dup bl = while drop key repeat ?quit ; : even begin word? while emit key repeat ; : odd word? if key recurse swap emit then ; : main cr key eatbl begin even eatbl space odd eatbl space again ;
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...
#Fortran
Fortran
MODULE ELUDOM !Uses the call stack for auxiliary storage. INTEGER MSG,INF !I/O unit numbers. LOGICAL DEFER !To stumble, or not to stumble. CONTAINS CHARACTER*1 RECURSIVE FUNCTION GET(IN) !Returns one character, going forwards. INTEGER IN !The input file. CHARACTER*1 ...
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...
#Applesoft_BASIC
Applesoft BASIC
100 LET M$ = CHR$ (13) 110 LET A$ = "123456789" 120 FOR S = 0 TO 1 STEP 0 130 LET N$ = A$ 140 FOR I = 1 TO 9 150 LET R = INT ( RND (1) * 9 + 1) 160 GOSUB 500SWAP 170 NEXT I 180 LET S = N$ < > A$ 190 NEXT S 200 FOR S = 1 TO 1E9 210 PRINT M$"HOW MANY DIGITS "...
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...
#ALGOL_W
ALGOL W
begin  % declare a record type - will be accessed via references  % record R( integer f1, f2, f3 );  % declare a reference to a R instance  % reference(R) refR;  % assign null to the reference  % refR := 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...
#AmigaE
AmigaE
DEF x : PTR TO object -> ... IF object <> NIL -> ... ENDIF
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...
#Befunge
Befunge
v " !!! !! ! ! ! !  ! " ,*25 <v " " ,*25,,,,,,,,,,,,,,,,,,,...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   double int_leftrect(double from, double to, double n, double (*func)()) { double h = (to-from)/n; double sum = 0.0, x; for(x=from; x <= (to-h); x += h) sum += func(x); return h*sum; }   double int_rightrect(double from, double to, double n, do...
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   ...
#FreeBASIC
FreeBASIC
function eqrf( n as uinteger ) as boolean dim as string sn = str(n) dim as integer q = 0 for i as uinteger = 2 to len(sn) if asc(mid(sn,i,1)) > asc(mid(sn,i-1,1)) then q += 1 elseif asc(mid(sn,i,1)) < asc(mid(sn,i-1,1)) then q -= 1 end if next i if ...
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   ...
#Go
Go
package main   import "fmt"   func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { ...
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 ...
#J
J
NB. returns coefficents for yth-order Legendre polynomial getLegendreCoeffs=: verb define M. if. y<:1 do. 1 {.~ - y+1 return. end. (%~ <:@(,~ +:) -/@:* (0;'') ,&> [: getLegendreCoeffs&.> -&1 2) y )   getPolyRoots=: 1 {:: p. NB. returns the roots of a polynomial getGaussLegendreWeights...
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   // a fantasy two level hierarchy @interface Animal : NSObject <NSCoding> { NSString *animalName; int numberOfLegs; } - (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs; - (void) dump; @end   @implementation Animal - (instancetype) initWithName: (NSString*)nam...
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...
#Common_Lisp
Common Lisp
(defun verse (what remark &optional always die) (list what remark always die)) (defun what (verse) (first verse)) (defun remark (verse) (second verse)) (defun always (verse) (third verse)) (defun die (verse) (fourth verse))   (defun ssa (what remark &optional always die ) (verse what (format nil "~a she swal...
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: ...
#Python
Python
from sys import argv   unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, "meter": 1.0, "milia": 7467.6, "piad": 0.1778, "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,...
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: ...
#Racket
Racket
  #lang racket   (define units '([tochka 0.000254] [liniya 0.00254] [diuym 0.0254] [vershok 0.04445] [piad 0.1778] [fut 0.3048] [arshin 0.7112] [sazhen 2.1336] [versta 1066.8] [milia 7467.6] [centimeter 0....
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.
#OCaml
OCaml
open GL open Glut   let display() = glClearColor 0.3 0.3 0.3 0.0; glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];   glShadeModel GL_SMOOTH;   glLoadIdentity(); glTranslate (-15.0) (-15.0) (0.0);   glBegin GL_TRIANGLES; glColor3 1.0 0.0 0.0; glVertex2 0.0 0.0; glColor3 0.0 1.0 0.0; glVertex2 30.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...
#Haskell
Haskell
import qualified Data.Map as M import System.Random import Data.List import Control.Monad import System.Environment   testFile = [1..10]   selItem g xs = foldl' f (head xs, 1, 2, g) $ tail xs where f :: RandomGen a => (b, Int, Int, a) -> b -> (b, Int, Int, a) f (c, cn, n, gen) l | v == 1 = (l, n, n+1, ...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() # one of n one_of_n_test(10,1000000) end   procedure one_of_n(n) every i := 1 to n do choice := (?0 < 1. / i, i) return \choice | fail end   procedure one_of_n_test(n,trials) bins := table(0) every i := 1 to trials do bins[one_of_n(n)] +:= 1 every writes(bins[i := 1 t...
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 ...
#PARI.2FGP
PARI/GP
sort(v, ordering=0, column=0, reverse=0)
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 ...
#Perl
Perl
sub sorttable {my @table = @{shift()}; my %opt = (ordering => sub {$_[0] cmp $_[1]}, column => 0, reverse => 0, @_); my $col = $opt{column}; my $func = $opt{ordering}; my @result = sort {$func->($a->[$col], $b->[$col])} @table; return ($opt{reverse} ? [reverse @result] : \@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...
#LabVIEW
LabVIEW
local( first = array(1,2,1,3,2), second = array(1,2,0,4,4,0,0,0), ) #first < #second   local( first = array(1,1,1,3,2), second = array(1,2,0,4,4,0,0,0), ) #first < #second
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...
#Lasso
Lasso
local( first = array(1,2,1,3,2), second = array(1,2,0,4,4,0,0,0), ) #first < #second   local( first = array(1,1,1,3,2), second = array(1,2,0,4,4,0,0,0), ) #first < #second
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...
#K
K
w@&d=|/d:#:'w:d@&&/'{~x<y}':'d:0:"unixdict.txt" ("abbott" "accent" "accept" "access" "accost" "almost" "bellow" "billow" "biopsy" "chilly" "choosy" "choppy" "effort" "floppy" "glossy" "knotty")
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...
#Kotlin
Kotlin
import java.io.File   fun main(args: Array<String>) { val file = File("unixdict.txt") val result = mutableListOf<String>()   file.forEachLine { if (it.toCharArray().sorted().joinToString(separator = "") == it) { result += it } }   result.sortByDescending { it.length } ...
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 ...
#Potion
Potion
# The readable recursive version palindrome_i = (s, b, e): if (e <= b): true. elsif (s ord(b) != s ord(e)): false. else: palindrome_i(s, b+1, e-1). .   palindrome = (s): palindrome_i(s, 0, s length - 1).   palindrome(argv(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...
#Haskell
Haskell
data Error a = Error {value :: a, uncertainty :: a} deriving (Eq, Show)   instance (Floating a) => Num (Error a) where Error a ua + Error b ub = Error (a + b) (sqrt (ua ^ 2 + ub ^ 2)) negate (Error a ua) = Error (negate a) ua Error a ua * Error b ub = Error (a * b) (abs (a * b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) ...
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...
#Go
Go
package main   import ( "bytes" "fmt" "io" "os" "unicode" )   func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() }   func owp(dst io.Writer, src io.Rea...
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...
#360_Assembly
360 Assembly
* Number names 20/02/2017 NUMNAME CSECT USING NUMNAME,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 end of prolog LA R6,1 i=1 DO...
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...
#Arturo
Arturo
arr: 1..9   while [arr = sort arr]-> arr: shuffle arr   score: 0 while [arr <> sort arr][ prints [arr "-- "] digits: to :integer strip input "How many digits to reverse? " arr: (reverse slice arr 0 digits-1) ++ slice arr digits (size arr)-1 score: score + 1 ]   print ["Your score:" score]
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...
#APL
APL
  ⍝⍝ GNU APL ]help ⍬ niladic function: Z ← ⍬ (Zilde) Zilde is the empty numeric vector (aka. ⍳0) Not a function but rather an alias for the empty vector: ⍬≡⍳0 1  
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...
#AppleScript
AppleScript
if x is missing value then display dialog "x is missing value" end if   if x is null then display dialog "x is null" end if
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...
#Bracmat
Bracmat
( ( evolve = n z . @( !arg  : %?n ? @?z  :  ? ( ( ( 000 | 001 | 010 | 100 | 111 ) & 0 !n:?n | (011|101|110) ...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public class Interval { public Interval(double leftEndpoint, double size) { LeftEndpoint = leftEndpoint; RightEndpoint = leftEndpoint + size; }   public double LeftEndpoint { get; set; }   pu...
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   ...
#Haskell
Haskell
import Data.Char   pairs :: [a] -> [(a,a)] pairs (a:b:as) = (a,b):pairs (b:as) pairs _ = []   riseEqFall :: Int -> Bool riseEqFall n = rel (>) digitPairs == rel (<) digitPairs where rel r = sum . map (fromEnum . uncurry r) digitPairs = pairs $ map digitToInt $ show n   a296712 :: [Int] a296712 = [...
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   ...
#Java
Java
public class EqualRisesFalls { public static void main(String[] args) { final int limit1 = 200; final int limit2 = 10000000; System.out.printf("The first %d numbers in the sequence are:\n", limit1); int n = 0; for (int count = 0; count < limit2; ) { if (equalRises...
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 ...
#Java
Java
import static java.lang.Math.*; import java.util.function.Function;   public class Test { final static int N = 5;   static double[] lroots = new double[N]; static double[] weight = new double[N]; static double[][] lcoef = new double[N + 1][N + 1];   static void legeCoef() { lcoef[0][0] = lco...
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...
#OCaml
OCaml
type entity = { name : string }   let create_entity () = { name = "Entity" } let print_entity x = print_endline x.name let create_person () = { name = "Cletus" }   let instance1 = create_person () let instance2 = create_entity ()   (* Serialize *) let out_chan = open_out_bin "objects.dat";; output_value out_chan instan...
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...
#Ol
Ol
  $ ol Welcome to Otus Lisp 1.2, type ',help' to help, ',quit' to end session. > (define Object (tuple '(1 2 3 4) ; list #(4 3 2 1) ; bytevector "hello" ; ansi string "こんにちは" ; unicode string (list->ff '(; associative array (1 . 123456) (2 . second) (3 . "-th-"))) {(4 . 'sym) ...