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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#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 = map { for (cell in `Cell`.caseValues) cell.character->cell };   shared class Automata1D({Cell*} initialCells) {     value permanentFirstCell = initialCells.first else dead; value permanentLastCell = initialCells.last else dead;   value cells = Array { *initialCells.rest.exceptLast };   shared Boolean evolve() {   value newCells = Array { for (index->cell in cells.indexed) let (left = cells[index - 1] else permanentFirstCell, right = cells[index + 1] else permanentLastCell, neighbours = [left, right], bothAlive = neighbours.every(alive.equals), bothDead = neighbours.every(dead.equals)) if (bothAlive) then cell.opposite else if (cell == alive && bothDead) then dead else cell };   if (newCells == cells) { return false; }   newCells.copyTo(cells); return true; }   string => permanentFirstCell.string + "".join(cells) + permanentLastCell.string; }   shared Automata1D? automata1d(String string) => let (cells = string.map((Character element) => cellsByCharacter[element])) if (cells.every((Cell? element) => element exists)) then Automata1D(cells.coalesced) else null;   shared void run() {   assert (exists automata = automata1d("__###__##_#_##_###__######_###_#####_#__##_____#_#_#######__"));   variable value generation = 0; print("generation ``generation`` ``automata``"); while (automata.evolve() && generation<10) { print("generation `` ++generation `` ``automata``"); } }
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 that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#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", fromval, toval, 100); 1070 PRINT USING "###.#########": numint(f1, "R", fromval, toval, 100); 1080 PRINT USING "###.#########": numint(f1, "M", fromval, toval, 100); 1090 PRINT USING "###.#########": numint(f1, "T", fromval, toval, 100); 1100 PRINT USING "###.#########": numint(f1, "S", fromval, toval, 100) 1110 // 1120 fromval:=1 1130 toval:=100 1140 PRINT "1/X "; 1150 PRINT USING "#####": fromval; 1160 PRINT USING "#####": toval; 1170 PRINT USING "###.#########": numint(f2, "L", fromval, toval, 1000); 1180 PRINT USING "###.#########": numint(f2, "R", fromval, toval, 1000); 1190 PRINT USING "###.#########": numint(f2, "M", fromval, toval, 1000); 1200 PRINT USING "###.#########": numint(f2, "T", fromval, toval, 1000); 1210 PRINT USING "###.#########": numint(f2, "S", fromval, toval, 1000) 1220 fromval:=0 1230 toval:=5000 1240 PRINT "X "; 1250 PRINT USING "#####": fromval; 1260 PRINT USING "#####": toval; 1270 PRINT USING "#########.###": numint(f3, "L", fromval, toval, 5000000); 1280 PRINT USING "#########.###": numint(f3, "R", fromval, toval, 5000000); 1290 PRINT USING "#########.###": numint(f3, "M", fromval, toval, 5000000); 1300 PRINT USING "#########.###": numint(f3, "T", fromval, toval, 5000000); 1310 PRINT USING "#########.###": numint(f3, "S", fromval, toval, 5000000) 1320 // 1330 fromval:=0 1340 toval:=6000 1350 PRINT "X "; 1360 PRINT USING "#####": fromval; 1370 PRINT USING "#####": toval; 1380 PRINT USING "#########.###": numint(f3, "L", fromval, toval, 6000000); 1390 PRINT USING "#########.###": numint(f3, "R", fromval, toval, 6000000); 1400 PRINT USING "#########.###": numint(f3, "M", fromval, toval, 6000000); 1410 PRINT USING "#########.###": numint(f3, "T", fromval, toval, 6000000); 1420 PRINT USING "#########.###": numint(f3, "S", fromval, toval, 6000000) 1430 END 1440 // 1450 FUNC numint(FUNC f, type$, lbound, rbound, iters) CLOSED 1460 delta:=(rbound-lbound)/iters 1470 integral:=0 1480 CASE type$ OF 1490 WHEN "L", "T", "S" 1500 actval:=lbound 1510 WHEN "M" 1520 actval:=lbound+delta/2 1530 WHEN "R" 1540 actval:=lbound+delta 1550 OTHERWISE 1560 actval:=lbound 1570 ENDCASE 1580 FOR n:=0 TO iters-1 DO 1590 CASE type$ OF 1600 WHEN "L", "M", "R" 1610 integral:+f(actval+n*delta)*delta 1620 WHEN "T" 1630 integral:+delta*(f(actval+n*delta)+f(actval+(n+1)*delta))/2 1640 WHEN "S" 1650 IF n=0 THEN 1660 sum1:=f(lbound+delta/2) 1670 sum2:=0 1680 ELSE 1690 sum1:+f(actval+n*delta+delta/2) 1700 sum2:+f(actval+n*delta) 1710 ENDIF 1720 OTHERWISE 1730 integral:=0 1740 ENDCASE 1750 ENDFOR 1760 IF type$="S" THEN 1770 RETURN (delta/6)*(f(lbound)+f(rbound)+4*sum1+2*sum2) 1780 ELSE 1790 RETURN integral 1800 ENDIF 1810 ENDFUNC 1820 // 1830 FUNC f1(x) CLOSED 1840 RETURN x^3 1850 ENDFUNC 1860 // 1870 FUNC f2(x) CLOSED 1880 RETURN 1/x 1890 ENDFUNC 1900 // 1910 FUNC f3(x) CLOSED 1920 RETURN x 1930 ENDFUNC  
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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 = $this % $base; $this = $this div $base; if $rem > $last { $fall = $fall + 1 } elsif $rem < $last { $rise = $rise + 1 } $last = $rem } next unless &op($rise, $fall); $_ } }   # The task my $upto = 200; put "Rise = Fall:\nFirst {$upto.&cardinal} (base 10):"; .put for rf[^$upto]».fmt("%3d").batch(20);   $upto = 10_000_000; put "\nThe {$upto.&ordinal} (base 10): ", comma rf(10, 65536)[$upto - 1];   # Other bases and comparisons put "\n\nGeneralized for other bases and other comparisons:"; $upto = ^5; my $which = "{tc $upto.map({.exp(10).&ordinal}).join: ', '}, values in some other bases:";   put "\nRise = Fall: $which"; for <3 296691 4 296694 5 296697 6 296700 7 296703 8 296706 9 296709 10 296712 11 296744 12 296747 13 296750 14 296753 15 296756 16 296759 20 296762 60 296765> -> $base, $oeis { put "Base {$base.fmt(<%2d>)} (https://oeis.org/A$oeis): ", $upto.map({rf(+$base, Any)[.exp(10) - 1].&to-base($base)}).join: ', ' }   put "\nRise > Fall: $which"; for <3 296692 4 296695 5 296698 6 296701 7 296704 8 296707 9 296710 10 296713 11 296745 12 296748 13 296751 14 296754 15 296757 16 296760 20 296763 60 296766> -> $base, $oeis { put "Base {$base.fmt(<%2d>)} (https://oeis.org/A$oeis): ", $upto.map({rf(+$base, Any, &infix:«>»)[.exp(10) - 1].&to-base($base)}).join: ', ' }   put "\nRise < Fall: $which"; for <3 296693 4 296696 5 296699 6 296702 7 296705 8 296708 9 296711 10 296714 11 296746 12 296749 13 296752 14 296755 15 296758 16 296761 20 296764 60 296767> -> $base, $oeis { put "Base {$base.fmt(<%2d>)} (https://oeis.org/A$oeis): ", $upto.map({rf(+$base, Any, &infix:«<»)[.exp(10) - 1].&to-base($base)}).join: ', ' }
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 W(x)} . ∫ − 1 1 f ( x ) d x = ∫ − 1 1 W ( x ) g ( x ) d x {\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx} Those are then approximated by a sum of function values at specified points x i {\displaystyle x_{i}} multiplied by some weights w i {\displaystyle w_{i}} : ∫ − 1 1 W ( x ) g ( x ) d x ≈ ∑ i = 1 n w i g ( x i ) {\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})} In the case of Gauss-Legendre quadrature, the weighting function W ( x ) = 1 {\displaystyle W(x)=1} , so we can approximate an integral of f ( x ) {\displaystyle f(x)} with: ∫ − 1 1 f ( x ) d x ≈ ∑ i = 1 n w i f ( x i ) {\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})} For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods. The n {\displaystyle n} evaluation points x i {\displaystyle x_{i}} for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials P n ( x ) {\displaystyle P_{n}(x)} . Legendre polynomials are defined by the following recursive rule: P 0 ( x ) = 1 {\displaystyle P_{0}(x)=1} P 1 ( x ) = x {\displaystyle P_{1}(x)=x} n P n ( x ) = ( 2 n − 1 ) x P n − 1 ( x ) − ( n − 1 ) P n − 2 ( x ) {\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)} There is also a recursive equation for their derivative: P n ′ ( x ) = n x 2 − 1 ( x P n ( x ) − P n − 1 ( x ) ) {\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)} The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration: x n + 1 = x n − f ( x n ) f ′ ( x n ) {\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}} The first guess x 0 {\displaystyle x_{0}} for the i {\displaystyle i} -th root of a n {\displaystyle n} -order polynomial P n {\displaystyle P_{n}} can be given by x 0 = cos ⁡ ( π i − 1 4 n + 1 2 ) {\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)} After we get the nodes x i {\displaystyle x_{i}} , we compute the appropriate weights by: w i = 2 ( 1 − x i 2 ) [ P n ′ ( x i ) ] 2 {\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}} After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval [ a , b ] {\displaystyle [a,b]} by ∫ a b f ( x ) d x ≈ b − a 2 ∑ i = 1 n w i f ( b − a 2 x i + a + b 2 ) {\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)} Task description Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function f ( x ) {\displaystyle f(x)} , but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison. To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute: ∫ − 3 3 exp ⁡ ( x ) d x ≈ ∑ i = 1 5 w i exp ⁡ ( x i ) ≈ 20.036 {\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
#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   local function legendreDerivative(term, z) if (term == 0) then return 0 elseif (term == 1) then return 1 else return ( term * ((z * legendre(term, z)) - legendre(term - 1, z))) / (z * z - 1) end end   local function getLegendreRoots() local y, y1   for index = 1, order do y = math.cos(math.pi * (index - 0.25) / (order + 0.5))   repeat y1 = y y = y - (legendre(order, y) / legendreDerivative(order, y)) until y == y1   table.insert(legendreRoots, y) end end   local function getLegendreWeights() for index = 1, order do local weight = 2 / ((1 - (legendreRoots[index]) ^ 2) * (legendreDerivative(order, legendreRoots[index])) ^ 2) table.insert(legendreWeights, weight) end end   function gaussLegendreQuadrature(f, lowerLimit, upperLimit, n) order = n   do getLegendreRoots() getLegendreWeights() end   local c1 = (upperLimit - lowerLimit) / 2 local c2 = (upperLimit + lowerLimit) / 2 local sum = 0   for i = 1, order do sum = sum + legendreWeights[i] * f(c1 * legendreRoots[i] + c2) end   return c1 * sum end   do print(gaussLegendreQuadrature(function(x) return math.exp(x) end, -3, 3, 5)) end
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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): print self.name   class Person(Entity): #OldMan inherits from Entity def __init__(self): #override constructor self.name = "Cletus"   instance1 = Person() instance1.printName()   instance2 = Entity() instance2.printName()   target = file("objects.dat", "w") # open file   # Serialize pickle.dump((instance1, instance2), target) # serialize `instance1` and `instance2`to `target` target.close() # flush file stream print "Serialized..."   # Unserialize target = file("objects.dat") # load again i1, i2 = pickle.load(target) print "Unserialized..."   i1.printName() i2.printName()
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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 string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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, to swallow a dog!" },_ { "goat", "She just opened her throat and swallowed a goat!" },_ { "cow", "I don't know how she swallowed a cow."},_ { "horse", "She's dead of course!" } }   for verse as ubyte = 0 to 7 for countdown as byte = verse to 0 step -1 if countdown = verse then print "There was an old lady who swallowed a "; lyrics(verse, 0);"." print lyrics(verse, 1) if verse = 7 then end end if if countdown > 0 then print "She swallowed the ";lyrics(countdown, 0);_ " to catch the ";lyrics(countdown-1, 0);"," if countdown = 2 or countdown = 1 then print lyrics(countdown-1, 1) next countdown print next verse
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: vershoks, arshins, sazhens, versts, meters, centimeters and kilometers. Also see   Old Russian measure of length
#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, 74676, 1, 100, 10000 ]   while (true) { var i = 0 for (u in units) { Fmt.print("$2d $s", i+1, u) i = i + 1 } System.print() var unit while (true) { System.write("Please choose a unit 1 to 13  : ") Stdout.flush() unit = Num.fromString(Stdin.readLine()) if (unit.type == Num && unit.isInteger && unit >= 1 && unit <= 13) break } unit = unit - 1 var value while (true) { System.write("Now enter a value in that unit : ") Stdout.flush() value = Num.fromString(Stdin.readLine()) if (value.type == Num && value >= 0) break } System.print("\nThe equivalent in the remaining units is:\n") i = 0 for (u in units) { if (i != unit) Fmt.print(" $10s : $15.8g", u, value*convs[unit]/convs[i]) i = i + 1 } System.print() var yn = "" while (yn != "y" && yn != "n") { System.write("Do another one y/n : ") Stdout.flush() yn = Str.lower(Stdin.readLine()) } if (yn == "n") break System.print() }
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) (glColor3f 1.0 0.0 0.0) (glVertex2f 0.0 0.0) (glColor3f 0.0 1.0 0.0) (glVertex2f 30.0 0.0) (glColor3f 0.0 0.0 1.0) (glVertex2f 0.0 30.0) (glEnd) (glFlush) )   (reshapeFunc '((Width Height) (glViewport 0 0 Width Height) (glMatrixMode GL_PROJECTION) (glLoadIdentity) (glOrtho -30.0 30.0 -30.0 30.0 -30.0 30.0) (glMatrixMode GL_MODELVIEW) ) )   # Exit upon mouse click (mouseFunc '((Btn State X Y) (bye)))   (glutMainLoop)
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); GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);   GL.glShadeModel(GL.GL_SMOOTH);   GL.glLoadIdentity(); GL.glTranslate(-15.0, -15.0, 0.0);   GL.glBegin(GL.GL_TRIANGLES); GL.glColor(1.0, 0.0, 0.0); GL.glVertex(0.0, 0.0); GL.glColor(0.0, 1.0, 0.0); GL.glVertex(30.0, 0.0); GL.glColor(0.0, 0.0, 1.0); GL.glVertex(0.0, 30.0); GL.glEnd();   GL.glFlush();   GLUE.swap_buffers(); Pike.DefaultBackend(0.0); sleep(0.01); } }
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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; end if; end do; fclose(fid); return(n); end proc;  
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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++; If[RandomReal[] < 1/n, selected = rec]]; Close[strm]; selected]
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 An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#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). */ do j=1 for words(options) /*examine all the words (options). */ x= word(options, j) select when datatype(x, 'W') then col= x / 1 /*normalize the number. */ when pos('=', x)==0 then order= x /*has it an equal sign? */ otherwise parse var x nam '=' value /*get value.*/ end /*select*/ end /*j*/   /*╔═══════════════════════════════════════════════════════════╗ ║ check for errors here: COL isn't a positive integer ···, ║ ║ REVERSE value isn't NO or YES, ║ ║ ORDER value is recognized ··· ║ ╚═══════════════════════════════════════════════════════════╝*/   ... main body of string sort here ...   return /*stick a fork in it, we're all done. */
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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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 '(1 2 3) '(1 2))) ; => false (print (lexorder '(1 2 3) '(1 2 3))) ; => false (print (lexorder '(1 2 3) '(1 2 8))) ; => 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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 := 2: elif len = longest then words(i) := word: i++: end if; end if; end do; for word in words do print(word); end do;
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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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   σf2 = σa2 + σb2 Multiplication/Division If   f = ca   or   f = ac       then   σf = |cσa| If   f = ab   or   f = a / b   then   σf2 = f2( (σa / a)2 + (σb / b)2) Exponentiation If   f = ac   then   σf = |fc(σa / a)| Caution: This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   a   and   b   are independent and so the formula for multiplication should not be applied to   a*a   for example.   See   the talk page   for some of the implications of this issue. Task details Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. Given coordinates and their errors: x1 = 100 ± 1.1 y1 = 50 ± 1.2 x2 = 200 ± 2.2 y2 = 100 ± 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = √   (x1 - x2)²   +   (y1 - y2)²   Print and display both   d   and its error. References A Guide to Error Propagation B. Keeney, 2005. Propagation of uncertainty Wikipedia. Related task   Quaternion type
#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(a)*b[2]]); div(a,b)=if(type(b)!="t_VEC", mult(a,1/b), mult(a,[1/b[1],b[2]/b[1]^2])); pow(a,b)=[a[1]^b, abs(a[1]^b*b*a[2]/a[1])]; x1=[100,1.1];y1=[50,1.2];x2=[200,2.2];y2=[100,2.3]; pow(add(pow(sub(x1,x2),2),pow(sub(y1,y2),2)),.5)
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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 the shape of a closure clos() = (writebyte(a); prev())   return odd(clos) end   function even() while true c = readbyte!() writebyte(c) if !isalpha(c) return c != '.' end end end   evn = false while evn ? odd() : even() evn = !evn end
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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.isLetter()) return doChar(odd, ::writeOut) if (odd) { if (f != null) f() print(ch) } return ch != '.' }   fun main(args: Array<String>) { repeat(2) { var b = true while (doChar(!b, null)) b = !b System.`in`.read() // remove '\n' from buffer println("\n") } }
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, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#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) 170 IF H > 0 AND H < D THEN R$ = S$(H) + " " + R$ 180 IF H > 9 AND H < 20 THEN R$ = T$(H - D) + " " + R$ 190 IF H > 19 AND H < C THEN S = H - D * INT(H / D) : R$ = U$(INT(H / D)) + MID$("-",1+(S=0),1) + S$(S) + " " + R$ 200 H = A - M * INT(A / M) 210 H = INT (H / C) 220 IF H THEN R$ = S$(H) + " HUNDRED " + R$ 230 A = INT(A / M) 240 IF A > 0 THEN H = A - M * INT(A / M) : IF H THEN R$ = V$(U) + " " + R$ 250 IF A > 0 THEN NEXT U 260 IF N < 0 THEN R$ = "NEGATIVE " + R$ 270 RETURN   280 DATA "", "TEN", "", "THOUSAND" 281 DATA "ONE", "ELEVEN", "", "MILLION" 282 DATA "TWO", "TWELVE", "TWENTY", "BILLION" 283 DATA "THREE", "THIRTEEN", "THIRTY", "TRILLION" 284 DATA "FOUR", "FOURTEEN", "FORTY", "QUADRILLION" 285 DATA "FIVE", "FIFTEEN", "FIFTY", "QUINTILLION" 286 DATA "SIX", "SIXTEEN", "SIXTY", "SEXTILLION" 287 DATA "SEVEN", "SEVENTEEN", "SEVENTY", "SEPTILLION" 288 DATA "EIGHT", "EIGHTEEN", "EIGHTY", "OCTILLION" 289 DATA "NINE", "NINETEEN", "NINETY", "NONILLION" 290 DATA "", "", "", "DECILLION"
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 reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#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 for i = 1 to 9 nums[i] = i next i   do #barajamos for i = 9 to 2 step -1 n = int(rand * i) + 1 if n <> i then a[i] = nums[i] nums[i] = nums[n] nums[n] = a[i] end if next i for i = 1 to 8 #nos aseguramos que no estén en orden if nums[i] > nums[i + 1] then exit do next i until false   do if intentos < 10 then print " "; print intentos; ": "; for i = 1 to 9 print nums[i];" "; next i   if not denuevo then exit do   input " -- Cuantos volteamos ", volteo if volteo < 0 or volteo > 9 then volteo = 0   for i = 1 to (volteo \ 2) a[i] = nums[volteo - i + 1] nums[volteo - i + 1] = nums[i] nums[i] = a[i] next i   denuevo = false #comprobamos el orden for i = 1 to 8 if nums[i] > nums[i + 1] then denuevo = true exit for end if next i   if volteo > 0 then intentos += 1 until false print chr(10) + chr(10) + " Necesitaste "; intentos; " intentos." end  
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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#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))) "#" "_"))) (str ncs (s/drop 1 cs))))))   (defn generate [n cells] (if (= n 0) '() (cons cells (generate (dec n) (next-gen cells)))))  
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 that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#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 from (+ a (/ d 2)) below b by d summing (funcall f x))))   (defun trapezium (f a b n &aux (d (/ (- b a) n))) (* (/ d 2) (+ (funcall f a) (* 2 (loop for x from (+ a d) below b by d summing (funcall f x))) (funcall f b))))   (defun simpson (f a b n) (loop with h = (/ (- b a) n) with sum1 = (funcall f (+ a (/ h 2))) with sum2 = 0 for i from 1 below n do (incf sum1 (funcall f (+ a (* h i) (/ h 2)))) do (incf sum2 (funcall f (+ a (* h i)))) finally (return (* (/ h 6) (+ (funcall f a) (funcall f b) (* 4 sum1) (* 2 sum2))))))
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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 /*a flag that is used to append numbers*/ n= abs(n) /*use the absolute value of N. */ call init /*initialize the rise/fall database. */ do j=1 until #==n /*test integers until we have N of them*/ s= 0 /*initialize the sum of rises/falls. */ do k=1 for length(j)-1 /*obtain a set of two digs from number.*/ t= substr(j, k, 2) /*obtain a set of two digs from number.*/ s= s + @.t /*sum the rises and falls in the number*/ end /*k*/ if s\==0 then iterate /*Equal # of rises & falls? Then add it*/ #= # + 1 /*bump the count of numbers found. */ if append then $= $ j /*append to the list of numbers found. */ end /*j*/   if append then call show /*display a list of N numbers──►term.*/ else say 'the ' commas(n)th(n) " number is: " commas(j) /*show Nth #.*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do c=length(_)-3 to 1 by -3; _=insert(',', _, c); end; return _ th: parse arg th; return word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4)) /*──────────────────────────────────────────────────────────────────────────────────────*/ init: @.= 0; do i=1 for 9; _= i' '; @._= 1; _= '0'i; @._= +1; end /*i*/ do i=10 to 99; parse var i a 2 b; if a>b then @.i= -1 else if a<b then @.i= +1 end /*i*/; #= 0; $=; return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: say 'the first ' commas(#) " numbers are:"; say; w= length( word($, #) ) _=; do o=1 for n; _= _ right( word($, o), w); if o//20\==0 then iterate say substr(_, 2); _= /*display a line; nullify a new line. */ end /*o*/ /* [↑] display 20 numbers to a line.*/   if _\=='' then say substr(_, 2); return /*handle any residual numbers in list. */
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 W(x)} . ∫ − 1 1 f ( x ) d x = ∫ − 1 1 W ( x ) g ( x ) d x {\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx} Those are then approximated by a sum of function values at specified points x i {\displaystyle x_{i}} multiplied by some weights w i {\displaystyle w_{i}} : ∫ − 1 1 W ( x ) g ( x ) d x ≈ ∑ i = 1 n w i g ( x i ) {\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})} In the case of Gauss-Legendre quadrature, the weighting function W ( x ) = 1 {\displaystyle W(x)=1} , so we can approximate an integral of f ( x ) {\displaystyle f(x)} with: ∫ − 1 1 f ( x ) d x ≈ ∑ i = 1 n w i f ( x i ) {\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})} For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods. The n {\displaystyle n} evaluation points x i {\displaystyle x_{i}} for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials P n ( x ) {\displaystyle P_{n}(x)} . Legendre polynomials are defined by the following recursive rule: P 0 ( x ) = 1 {\displaystyle P_{0}(x)=1} P 1 ( x ) = x {\displaystyle P_{1}(x)=x} n P n ( x ) = ( 2 n − 1 ) x P n − 1 ( x ) − ( n − 1 ) P n − 2 ( x ) {\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)} There is also a recursive equation for their derivative: P n ′ ( x ) = n x 2 − 1 ( x P n ( x ) − P n − 1 ( x ) ) {\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)} The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration: x n + 1 = x n − f ( x n ) f ′ ( x n ) {\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}} The first guess x 0 {\displaystyle x_{0}} for the i {\displaystyle i} -th root of a n {\displaystyle n} -order polynomial P n {\displaystyle P_{n}} can be given by x 0 = cos ⁡ ( π i − 1 4 n + 1 2 ) {\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)} After we get the nodes x i {\displaystyle x_{i}} , we compute the appropriate weights by: w i = 2 ( 1 − x i 2 ) [ P n ′ ( x i ) ] 2 {\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}} After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval [ a , b ] {\displaystyle [a,b]} by ∫ a b f ( x ) d x ≈ b − a 2 ∑ i = 1 n w i f ( b − a 2 x i + a + b 2 ) {\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)} Task description Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function f ( x ) {\displaystyle f(x)} , but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison. To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute: ∫ − 3 3 exp ⁡ ( x ) d x ≈ ∑ i = 1 5 w i exp ⁡ ( x i ) ≈ 20.036 {\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
#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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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 - $!lower.x) * ( $!upper.y - $!lower.y); } }   my $r1 = Rectangle.new(lower => Point.new(x => 0, y => 0), upper => Point.new(x => 10, y => 10)); say "Create Rectangle1 with area ",$r1.area(); say "Serialize Rectangle1 to object.dat"; $r1.to_file('./objects.dat'); say ""; say "take a peek on object.dat .."; say slurp "./objects.dat"; say ""; say "Deserialize to Rectangle2"; my $r2 = from_file('objects.dat'); say "Rectangle2 is of type ", $r2.WHAT; say "Rectangle2 area is ", $r2.area();
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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 end   class Earthling < Being def to_s4Being "I originate from a blue planet.\n"+" "*12+to_s4Earthling end end   class Mammal < Earthling def initialize(type) @type=type end def to_s4Earthling "I am champion in taking care of my offspring and eating everything I can find, except mammals of type #{@type}." end end   class Fish < Earthling def initialize(iq) @iq=(iq>1 ? :instrustableValue : iq) end def to_s4Earthling "Although I think I can think, I can't resist biting in hooks." end end   class Moonling < Being def to_s4Being "My name is Janneke Maan, and apparently some Earthlings will pay me a visit." end end   diverseCollection=[] diverseCollection << (marsian=Being.new("I come from Mars and like playing hide and seek.")) diverseCollection << (me=Mammal.new(:human)) diverseCollection << (nemo=Fish.new(0.99)) diverseCollection << (jannakeMaan=Moonling.new)   puts "BEGIN ORIGINAL DIVERSE COLLECTION" diverseCollection.each do |being| puts "",being.to_s end puts "END ORIGINAL DIVERSE COLLECTION" puts "\n"+"*"*50+"\n\n"   #Marshal the diverse Array of beings File.open('diverseCollection.bin','w') do |fo| fo << Marshal.dump(diverseCollection) end   #load the Array of diverse beings sameDiverseCollection=Marshal.load(File.read('diverseCollection.bin'))   puts "BEGIN LOADED DIVERSE COLLECTION" puts( sameDiverseCollection.collect do |being| being.to_s end.join("\n\n") ) puts "END LOADED DIVERSE COLLECTION"
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 string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 'fly', 'spider', 'bird', 'cat', 'dog', 'pig', 'goat', 'cow', 'donkey', 'horse' );   Verse1 = 'There was an old lady who swallowed a %s;'; //Verse 2 variations Verse2Var1 = '  %s'; //Doubles as a spacing formatter Verse2Var2 = '  %s to swallow a %s;'; Verse2Var3 = '  %s and swallowed a %s'; Verse2Var4 = '  %s she swallowed a %s'; Verse3 = ' She swallowed the %s to catch the %s;'; VerseEnd = 'I don''t know why she swallowed a fly - perhaps she''ll die!'; SongEnd = ' ...She''s dead of course!';   SwallowResult: array[1..MaxLadies] of shortstring = ( VerseEnd, 'That wiggled and jiggled and tickled inside her!', 'Quite absurd', 'Fancy that', 'What a hog,', 'Her mouth was so big', 'She just opened her throat', 'I don''t know how', 'It was rather wonky' );   procedure PrintSong; var i, j: byte; SwallowStr: shortstring;   begin for i := 1 to MaxLadies do begin WriteLn(Format(Verse1, [Animals[i]])); case i of 1..2: SwallowStr := Verse2Var1; 3..5: SwallowStr := Verse2Var2; 6, 8..9: SwallowStr := Verse2Var4; else SwallowStr := Verse2Var3; end; WriteLn(Format(SwallowStr, [SwallowResult[i], Animals[i]])); if i >= 2 then begin for j := i downto 2 do begin WriteLn(Format(Verse3, [Animals[j], Animals[j - 1]])); if (j - 1 = 2) and (i >= 3) then WriteLn(Format(Verse2Var1, [SwallowResult[2]])); end; if j >= 2 then WriteLn(Format(Verse2Var1, [VerseEnd])); end; end; WriteLn(Format(Verse1, [Animals[MaxLadies + 1]])); WriteLn(SongEnd); end;   begin PrintSong; 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 string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 verse. -- Die is only used for the horse, and means the chain of animals won't be -- included in the verse. data AnimalAction = Once | Every | Die   animals = [("horse", Die, "She's dead, of course!"), ("donkey", Once, "It was rather wonky. To swallow a donkey."), ("cow", Once, "I don't know how. To swallow a cow."), ("goat", Once, "She just opened her throat. To swallow a goat."), ("pig", Once, "Her mouth was so big. To swallow a pig."), ("dog", Once, "What a hog. To swallow a dog."), ("cat", Once, "Fancy that. To swallow a cat."), ("bird", Once, "Quite absurd. To swallow a bird."), ("spider", Once, "That wriggled and jiggled and tickled inside her."), ("fly", Every, "I don't know why she swallowed the fly.")]   verse :: [(String, AnimalAction, String)] -> [String] verse ((anim, act, phrase):restAnims) = let lns = ["I know an old lady who swallowed a " ++ anim ++ ".", phrase] in case act of Die -> lns _ -> lns ++ verse' restAnims anim   verse' :: [(String, AnimalAction, String)] -> String -> [String] verse' [] _ = ["Perhaps she'll die."] verse' ((anim, act, phrase):restAnims) prevAnim = let why = "She swallowed the " ++ prevAnim ++ " to catch the " ++ anim ++ "." lns = case act of Every -> [why, phrase] _ -> [why] in lns ++ verse' restAnims anim   song :: [String] song = concatMap verse $ tail $ reverse $ tails animals   main = putStr $ unlines song
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(PIXELFORMATDESCRIPTOR) pfd\nVersion = 1 pfd\dwFlags = #PFD_SUPPORT_OPENGL | #PFD_DOUBLEBUFFER | #PFD_DRAW_TO_WINDOW pfd\dwLayerMask = #PFD_MAIN_PLANE pfd\iPixelType = #PFD_TYPE_RGBA pfd\cColorBits = 24 pfd\cDepthBits = 16 pixformat = ChoosePixelFormat_(hdc, pfd) SetPixelFormat_(hdc, pixformat, pfd) hrc = wglCreateContext_(hdc) wglMakeCurrent_(hdc,hrc) glViewport_ (0, 0, WindowWidth-30, WindowHeight-30) glPushMatrix_() glMatrixMode_(#GL_MODELVIEW) glBegin_(#GL_TRIANGLES ); glColor3f_(1.0, 0.0, 0.0 ) glVertex2f_( 0.0, 1.0 ) glColor3f_( 0.0, 1.0, 0.0 ) glVertex2f_( 0.87, -0.5 ); glColor3f_( 0.0, 0.0, 1.0 ) glVertex2f_( -0.87, -0.5 ); glEnd_() glPopMatrix_() glFinish_() SwapBuffers_(hdc) While Quit = 0 Repeat EventID = WindowEvent() Select EventID Case #PB_Event_CloseWindow Quit = 1 EndSelect Until EventID = 0 Wend    
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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 An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#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 An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#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, reverse: false, ordering_function: |str1, str2| str1.cmp(str2), } } }   impl Table { fn with_ordering_column(&mut self, ordering_column: usize) -> &mut Table { self.ordering_column = ordering_column; self }   fn with_reverse(&mut self, reverse: bool) -> &mut Table { self.reverse = reverse; self }   fn with_ordering_fun(&mut self, compare: fn(&str, &str) -> Ordering) -> &mut Table { self.ordering_function = compare; self }   fn sort(&mut self) { let fun = &mut self.ordering_function; let idx = self.ordering_column; if self.reverse { self.rows .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx]).reverse()); } else { self.rows .sort_unstable_by(|vec1, vec2| (fun)(&vec1[idx], &vec2[idx])); } } }   #[cfg(test)] mod test { use super::Table;   fn generate_test_table() -> Table { Table::new(vec![ vec!["0".to_string(), "fff".to_string()], vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], ]) }   #[test] fn test_simple_sort() { let mut table = generate_test_table(); table.sort(); assert_eq!( table.rows, vec![ vec!["0".to_string(), "fff".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["2".to_string(), "aab".to_string()], ], ) }   #[test] fn test_ordering_column() { let mut table = generate_test_table(); table.with_ordering_column(1).sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) }   #[test] fn test_with_reverse() { let mut table = generate_test_table(); table.with_reverse(true).sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) }   #[test] fn test_custom_ordering_fun() { let mut table = generate_test_table(); // Simple ordering function that reverses stuff. // Should operate like the test before. table.with_ordering_fun(|x, y| x.cmp(y).reverse()).sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) }   #[test] fn test_everything_together() { let mut table = generate_test_table(); // Using the reversing cmp function, then reverse (= don't do anything) // then sort from column 1. table .with_ordering_fun(|x, y| x.cmp(y).reverse()) .with_reverse(true) .with_ordering_column(1) .sort(); assert_eq!( table.rows, vec![ vec!["2".to_string(), "aab".to_string()], vec!["1".to_string(), "ccc".to_string()], vec!["0".to_string(), "fff".to_string()], ], ) } }  
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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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; } if ($first > $second) { return 0; } } else { return 0; } }   @{$secondlist} ? 1 : 0; }   foreach my $pair ( [[1, 2, 4], [1, 2, 4]], [[1, 2, 4], [1, 2, ]], [[1, 2, ], [1, 2, 4]], [[55,53,1], [55,62,83]], [[20,40,51],[20,17,78,34]], ) { my $first = $pair->[0]; my $second = $pair->[1]; my $before = orderlists([@$first], [@$second]) ? 'true' : 'false'; print "(@$first) comes before (@$second) : $before\n"; }
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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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   σf2 = σa2 + σb2 Multiplication/Division If   f = ca   or   f = ac       then   σf = |cσa| If   f = ab   or   f = a / b   then   σf2 = f2( (σa / a)2 + (σb / b)2) Exponentiation If   f = ac   then   σf = |fc(σa / a)| Caution: This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   a   and   b   are independent and so the formula for multiplication should not be applied to   a*a   for example.   See   the talk page   for some of the implications of this issue. Task details Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. Given coordinates and their errors: x1 = 100 ± 1.1 y1 = 50 ± 1.2 x2 = 200 ± 2.2 y2 = 100 ± 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = √   (x1 - x2)²   +   (y1 - y2)²   Print and display both   d   and its error. References A Guide to Error Propagation B. Keeney, 2005. Propagation of uncertainty Wikipedia. Related task   Quaternion type
#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 '""' => \&_str, '+' => \&_add, '-' => \&_sub, '*' => \&_mul, '/' => \&_div, 'bool' => \&_bool, '<=>' => \&_ncmp, 'neg' => \&_neg,   'sqrt' => \&_sqrt, 'log' => \&_log, 'exp' => \&_exp, '**' => \&_pow, ;   # make a variable with mean value and a list of coefficient to # variables providing independent errors sub make { my $x = shift; bless [$x, [@{+shift}]] }   sub _str { sprintf "%g±%.3g", $_[0][0], sigma($_[0]) }   # mean value of the var, or just the input if it's not of this class sub mean { my $x = shift; ref($x) && $x->isa(__PACKAGE__) ? $x->[0] : $x }   # return variance index array sub vlist { my $x = shift; ref($x) && $x->isa(__PACKAGE__) ? $x->[1] : []; }   sub variance { my $x = shift; return 0 unless ref($x) and $x->isa(__PACKAGE__); my $s; $s += $_ * $_ for (@{$x->[1]}); $s }   sub covariance { my ($x, $y) = @_; return 0 unless ref($x) && $x->isa(__PACKAGE__); return 0 unless ref($y) && $y->isa(__PACKAGE__);   my $s; zip { $s += $a * $b } vlist($x), vlist($y); $s }   sub sigma { sqrt variance(shift) }   # to determine if a var is probably zero. we use 1σ here sub _bool { my $x = shift; return abs(mean($x)) > sigma($x); }   sub _ncmp { my $x = shift() - shift() or return 0; return mean($x) > 0 ? 1 : -1; }   sub _neg { my $x = shift; bless [ -mean($x), [map(-$_, @{vlist($x)}) ] ]; }   sub _add { my ($x, $y) = @_; my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); bless [$x0 + $y0, zip {$a + $b} $xv, $yv]; }   sub _sub { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) } my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y)); bless [$x0 - $y0, zip {$a - $b} $xv, $yv]; }   sub _mul { my ($x, $y) = @_; my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y));   $xv = [ map($y0 * $_, @$xv) ]; $yv = [ map($x0 * $_, @$yv) ];   bless [$x0 * $y0, zip {$a + $b} $xv, $yv]; }   sub _div { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) }   my ($x0, $y0) = (mean($x), mean($y)); my ($xv, $yv) = (vlist($x), vlist($y));   $xv = [ map($_/$y0, @$xv) ]; $yv = [ map($x0 * $_/$y0/$y0, @$yv) ];   bless [$x0 / $y0, zip {$a + $b} $xv, $yv]; }   sub _sqrt { my $x = shift; my $x0 = mean($x); my $xv = vlist($x); $x0 = sqrt($x0); $xv = [ map($_ / 2 / $x0, @$xv) ]; bless [$x0, $xv] }   sub _pow { my ($x, $y, $swap) = @_; if ($swap) { ($x, $y) = ($y, $x) } if ($x < 0) { if (int($y) != $y || ($y & 1)) { die "Can't take pow of negative number $x"; } $x = -$x; } exp($y * log $x) }   sub _exp { my $x = shift; my $x0 = exp(mean($x)); my $xv = vlist($x); bless [ $x0, [map($x0 * $_, @$xv) ] ] }   sub _log { my $x = shift; my $x0 = mean($x); my $xv = vlist($x); bless [ log($x0), [ map($_ / $x0, @$xv) ] ] }   "If this package were to be in its own file, you need some truth value to end it like this.";   package main;   sub e { ErrVar::make @_ };   # x1 is of mean value 100, containing error 1.1 from source 1, etc. # all error sources are independent. my $x1 = e 100, [1.1, 0, 0, 0 ]; my $x2 = e 200, [0, 2.2, 0, 0 ]; my $y1 = e 50, [0, 0, 1.2, 0 ]; my $y2 = e 100, [0, 0, 0, 2.3];   my $z1 = sqrt(($x1 - $x2) ** 2 + ($y1 - $y2) ** 2); print "distance: $z1\n\n";   # this is not for task requirement my $a = $x1 + $x2; my $b = $y1 - 2 * $x2; print "covariance between $a and $b: ", $a->covariance($b), "\n";
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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(#str->isAlpha(#pos+#lastpos) && #pos+#lastpos <= #str->size) => { #lastpos++ } 'odd lastpos: '+#lastpos+'\r' local(maxpos = #pos+#lastpos-1) while(#invpos < (#lastpos+1)/2) => { local(i,o,ipos,opos) #ipos = #pos+#invpos #opos = #pos+(#lastpos-#invpos) #i = #str->get(#ipos) #o = #str->get(#opos)   //'switching '+#i+' and '+#o+'\r'   //'insert '+#o+' at '+(#ipos)+'\r' #str = string_insert(#str,-position=(#ipos),-text=#o)   //'remove redundant pos '+(#ipos+1)+'\r' #str->remove(#ipos+1,1)   //'insert '+#i+' at '+(#opos)+'\r' #str = string_insert(#str,-position=(#opos),-text=#i)   //'remove redundant pos '+(#opos+1)+'\r' #str->remove(#opos+1,1)   #invpos++ } #pos += #lastpos - 1 } //#str->get(#pos) + #isodd + '\r' #pos += 1 } return #str }   'orig:\rwhat,is,the;meaning,of:life.\r' 'new:\r' odd_word_processor('what,is,the;meaning,of:life.') '\rShould have:\rwhat,si,the;gninaem,of:efil.'
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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 if ch == "." then return false end end return true end   while forward() do end
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, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#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" IfMsgBox Cancel, Break }   Spell(n) { ; recursive function to spell out the name of a max 36 digit integer, after leading 0s removed Static p1=" thousand ",p2=" million ",p3=" billion ",p4=" trillion ",p5=" quadrillion ",p6=" quintillion " , p7=" sextillion ",p8=" septillion ",p9=" octillion ",p10=" nonillion ",p11=" decillion " , t2="twenty",t3="thirty",t4="forty",t5="fifty",t6="sixty",t7="seventy",t8="eighty",t9="ninety" , o0="zero",o1="one",o2="two",o3="three",o4="four",o5="five",o6="six",o7="seven",o8="eight" , o9="nine",o10="ten",o11="eleven",o12="twelve",o13="thirteen",o14="fourteen",o15="fifteen" , o16="sixteen",o17="seventeen",o18="eighteen",o19="nineteen"   n :=RegExReplace(n,"^0+(\d)","$1") ; remove leading 0s from n   If (11 < d := (StrLen(n)-1)//3) ; #of digit groups of 3 Return "Number too big"   If (d) ; more than 3 digits Return Spell(SubStr(n,1,-3*d)) p%d% ((s:=SubStr(n,1-3*d)) ? ", " Spell(s) : "")   i := SubStr(n,1,1) If (n > 99) ; 3 digits Return o%i% " hundred" ((s:=SubStr(n,2)) ? " and " Spell(s) : "")   If (n > 19) ; n = 20..99 Return t%i% ((o:=SubStr(n,2)) ? "-" o%o% : "")   Return o%n% ; n = 0..19 }   PrettyNumber(n) { ; inserts thousands separators into a number string Return RegExReplace( RegExReplace(n,"^0+(\d)","$1"), "\G\d+?(?=(\d{3})+(?:\D|$))", "$0,") }
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 reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#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=123456789   ::Generating a random set of 9 digits... set cyc=9 :gen set /a tmp1=%random%%%%cyc% set n%cyc%=!list:~%tmp1%,1! set tmp2=!n%cyc%! set list=!list:%tmp2%=! if not %cyc%==2 ( set /a cyc-=1 goto :gen ) set /a n1=%list% ::Display the Game cls echo. echo ***Number Reversal Game*** :loopgame echo. echo Current arrangement: %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9% set /p move=How many digits from the left should I reverse? ::Reverse digits according to the player's input ::NOTE: The next command uses the fact that in Batch File, ::The output for the division operation is only the integer part of the quotient. set /a lim=(%move%+1)/2   set cyc2=1 :reverse set /a tmp4=%move%-%cyc2%+1 set tmp5=!n%cyc2%! set n%cyc2%=!n%tmp4%! set n%tmp4%=%tmp5% if not %cyc2%==%lim% ( set /a cyc2+=1 goto :reverse ) ::Increment the number of moves took by the player set /a score+=1 ::IF already won... if %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9%==123456789 ( echo. echo Set: %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9% DONE^^! echo You took %score% moves to arrange the numbers in ascending order. pause>nul exit ) else ( goto :loopgame )  
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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#COBOL
COBOL
  Identification division. Program-id. rc-1d-cell.   Data division. Working-storage section.   *> "Constants." 01 max-gens pic 999 value 9. 01 state-width pic 99 value 20. 01 state-table-init pic x(20) value ".@@@.@@.@.@.@.@..@..". 01 alive pic x value "@". 01 dead pic x value ".".   *> The current state. 01 state-gen pic 999 value 0. 01 state-row. 05 state-row-gen pic zz9. 05 filler pic xx value ": ". 05 state-table. 10 state-cells pic x occurs 20 times.   *> The new state. 01 new-state-table. 05 new-state-cells pic x occurs 20 times.   *> Pointer into cell table during generational production. 01 cell-index pic 99. 88 at-beginning value 1. 88 is-inside values 2 thru 19. 88 at-end value 20.   *> The cell's neighborhood. 01 neighbor-count-def. 03 neighbor-count pic 9. 88 is-comfy value 1. 88 is-ripe value 2.   Procedure division. Perform Init-state-table. Perform max-gens times perform Display-row perform Next-state end-perform. Perform Display-row. Stop run.   Display-row. Move state-gen to state-row-gen. Display state-row.   *> Determine who lives and who dies. Next-state. Add 1 to state-gen. Move state-table to new-state-table.   Perform with test after varying cell-index from 1 by 1 until at-end perform Count-neighbors perform Die-off perform New-births end-perform   move new-state-table to state-table.   *> Living cell with wrong number of neighbors... Die-off. if state-cells(cell-index) = alive and not is-comfy then move dead to new-state-cells(cell-index) end-if .   *> Empty cell with exactly two neighbors are... New-births. if state-cells(cell-index) = dead and is-ripe then move alive to new-state-cells(cell-index) end-if . *> How many living neighbors does a cell have? Count-neighbors. Move 0 to neighbor-count if at-beginning or at-end then add 1 to neighbor-count else if is-inside and state-cells(cell-index - 1) = alive then add 1 to neighbor-count end-if if is-inside and state-cells(cell-index + 1) = alive then add 1 to neighbor-count end-if end-if .   *> String is easier to enter, but table is easier to work with, *> so move each character of the initialization string to the *> state table.   Init-state-table. Perform with test after varying cell-index from 1 by 1 until at-end move state-table-init(cell-index:1) to state-cells(cell-index) end-perform .  
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 that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#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(f, a + h * i, h); return h * s; } }   double rectangularLeft(F, Float)(in F f, in Float x, in Float h) pure nothrow { return f(x); }   double rectangularMiddle(F, Float)(in F f, in Float x, in Float h) pure nothrow { return f(x + h / 2); }   double rectangularRight(F, Float)(in F f, in Float x, in Float h) pure nothrow { return f(x + h); }   double trapezium(F, Float)(in F f, in Float x, in Float h) pure nothrow { return (f(x) + f(x + h)) / 2; }   double simpson(F, Float)(in F f, in Float x, in Float h) pure nothrow { return (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6; }   void main() { immutable args = [ tuple((double x) => x ^^ 3, 0.0, 1.0, 10), tuple((double x) => 1 / x, 1.0, 100.0, 1000), tuple((double x) => x, 0.0, 5_000.0, 5_000_000), tuple((double x) => x, 0.0, 6_000.0, 6_000_000)];   alias TypeTuple!(integrate!rectangularLeft, integrate!rectangularMiddle, integrate!rectangularRight, integrate!trapezium, integrate!simpson) ints;   alias TypeTuple!("rectangular left: ", "rectangular middle: ", "rectangular right: ", "trapezium: ", "simpson: ") names;   foreach (a; args) { foreach (i, n; names) writefln("%s %f", n, ints[i](a.tupleof)); writeln(); } }
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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(' ') }) }   with (1e7) {|n| # takes a very long time say "\nThe #{n.commify}-th term (base #{base}): #{ n.th { isok(.digits(base)) && .is_pos }.commify}" }
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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 { total -= 1 } previousDigit = digit } return total == 0 }   var count = 0 var n = 0 let limit1 = 200 let limit2 = 10000000 print("The first \(limit1) numbers in the sequence are:") while count < limit2 { n += 1 if equalRisesAndFalls(n) { count += 1 if count <= limit1 { print(String(format: "%3d", n), terminator: count % 20 == 0 ? "\n" : " ") } } } print("\nThe \(limit2)th number in the sequence is \(n).")
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 W(x)} . ∫ − 1 1 f ( x ) d x = ∫ − 1 1 W ( x ) g ( x ) d x {\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx} Those are then approximated by a sum of function values at specified points x i {\displaystyle x_{i}} multiplied by some weights w i {\displaystyle w_{i}} : ∫ − 1 1 W ( x ) g ( x ) d x ≈ ∑ i = 1 n w i g ( x i ) {\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})} In the case of Gauss-Legendre quadrature, the weighting function W ( x ) = 1 {\displaystyle W(x)=1} , so we can approximate an integral of f ( x ) {\displaystyle f(x)} with: ∫ − 1 1 f ( x ) d x ≈ ∑ i = 1 n w i f ( x i ) {\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})} For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods. The n {\displaystyle n} evaluation points x i {\displaystyle x_{i}} for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials P n ( x ) {\displaystyle P_{n}(x)} . Legendre polynomials are defined by the following recursive rule: P 0 ( x ) = 1 {\displaystyle P_{0}(x)=1} P 1 ( x ) = x {\displaystyle P_{1}(x)=x} n P n ( x ) = ( 2 n − 1 ) x P n − 1 ( x ) − ( n − 1 ) P n − 2 ( x ) {\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)} There is also a recursive equation for their derivative: P n ′ ( x ) = n x 2 − 1 ( x P n ( x ) − P n − 1 ( x ) ) {\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)} The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration: x n + 1 = x n − f ( x n ) f ′ ( x n ) {\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}} The first guess x 0 {\displaystyle x_{0}} for the i {\displaystyle i} -th root of a n {\displaystyle n} -order polynomial P n {\displaystyle P_{n}} can be given by x 0 = cos ⁡ ( π i − 1 4 n + 1 2 ) {\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)} After we get the nodes x i {\displaystyle x_{i}} , we compute the appropriate weights by: w i = 2 ( 1 − x i 2 ) [ P n ′ ( x i ) ] 2 {\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}} After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval [ a , b ] {\displaystyle [a,b]} by ∫ a b f ( x ) d x ≈ b − a 2 ∑ i = 1 n w i f ( b − a 2 x i + a + b 2 ) {\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)} Task description Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function f ( x ) {\displaystyle f(x)} , but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison. To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute: ∫ − 3 3 exp ⁡ ( x ) d x ≈ ∑ i = 1 5 w i exp ⁡ ( x i ) ≈ 20.036 {\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
#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 polynomials used (number of integration ponts) [x_IP,weight]=GLGD_para(n); %assign global coordinates to the integraton points x_eval=x_IP*(xmax-xmin)/2+(xmax+xmin)/2; y=0; for aa=1:n y=y+feval(fun,x_eval(aa))*weight(aa)*(xmax-xmin)/2; end end   function [x_IP,weight]=GLGD_para(n) %n: the order of the polynomial x_IP=legendreRoot(n,10^(-16)); weight=2./(1-x_IP.^2)./diff_legendrePoly(x_IP,n).^2; end   %roots of the Legendre Polynomial using Newton-Raphson function x_IP=legendreRoot(n,tol) %n: order of the polynomial %tol: tolerence of the error if n<2 disp('No root can be found'); else root=zeros(1,floor(n/2)); for aa=1:floor(n/2) %iterate to find half of the roots x=cos(pi*(aa-0.25)/(n+0.5)); err=10*tol; iter=0; while (err>tol)&&(iter<1000) dx=-legendrePoly(x,n)/diff_legendrePoly(x,n); x=x+dx; iter=iter+1; err=abs(legendrePoly(x,n)); end root(aa)=x; end if mod(n,2)==0 x_IP=[-1*root,root]; else x_IP=[-1*root,0,root]; end x_IP=sort(x_IP); end end   %derivative of the Legendre Polynomial function y=diff_legendrePoly(x_IP,n) %n: order of the polynomial %x_IP: coordinates of the integration points if n==0 y=0; else y=n./(x_IP.^2-1).*(x_IP.*legendrePoly(x_IP,n)-legendrePoly(x_IP,n-1)); end end   %Produces Legendre Polynomials function y=legendrePoly(x,n) %n: order of polynomial %x: input x if n==0 y=1; elseif n==1 y=x; else y=((2*n-1).*x.*legendrePoly(x,n-1)-(n-1)*legendrePoly(x,n-2))/n; end end  
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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 { superclass Greeting oo::serializable variable v constructor {} { set v "Hello world from Junior!" } } oo::class create GreetingsHolder { superclass oo::serializable variable o1 o2 constructor {greeting1 greeting2} { set o1 $greeting1 set o2 $greeting2 } method printGreetings {} { puts [$o1 get] puts [$o2 get] } destructor { $o1 destroy $o2 destroy } }   # Make some objects and store them GreetingsHolder create holder [Greeting new] [SubGreeting new] set f [open "objects.dat" w] puts $f [oo::serialize holder] close $f   # Delete the objects holder destroy   # Recreate the objects from the file and show that they work set f [open "objects.dat" r] set obj [oo::deserialize [read $f]] close $f $obj printGreetings
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 string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 hog, to swallow a dog."}, {"goat", "She just opened her throat and swallowed that goat."}, {"cow", "I don't know how she swallowed that cow."}, {"horse", "She's dead, of course."}, }   func main() { for i, animal := range animals { fmt.Printf("There was an old lady who swallowed a %s,\n", animal[name])   if i > 0 { fmt.Println(animal[lyric]) }   // Swallowing the last animal signals her death, cutting the // lyrics short. if i+1 == len(animals) { break }   for ; i > 0; i-- { fmt.Printf("She swallowed the %s to catch the %s,\n", animals[i][name], animals[i-1][name]) }   fmt.Println(animals[0][lyric] + "\n") } }
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) glColor3f(1.0, 0.0, 0.0) glVertex2f(0.0, 0.0) glColor3f(0.0, 1.0, 0.0) glVertex2f(30.0, 0.0) glColor3f(0.0, 0.0, 1.0) glVertex2f(0.0, 30.0) glEnd()   glFlush()   def reshape(width, height): glViewport(0, 0, width, height) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) glMatrixMode(GL_MODELVIEW)   if __name__ == '__main__': glutInit(1, 1) glutInitWindowSize(640, 480) glutCreateWindow("Triangle")   glutDisplayFunc(paint) glutReshapeFunc(reshape)   glutMainLoop()
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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.printf " %d") ar; print_newline ()   let () = Random.self_init (); test ~n:10 ~trials:1_000_000
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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 An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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.txt").read() if is_ordered(word) if len(word) > longest longest = len(word) words.clear() words.append(word) else if len(word) = longest words.append(word) end end end println words
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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 do dwords.add(dword) if dword.length > wmax then wmax = dword.length end end ln inrdr.close   witerator = dwords.listIterator loop label wd while witerator.hasNext dword = Rexx witerator.next if dword.length < wmax then do witerator.remove end end wd dwords.trimToSize   say dwords.toString   catch ex = IOException ex.printStackTrace end   return   method isOrdered(dword = String) inheritable static binary returns boolean wchars = dword.toCharArray Arrays.sort(wchars) return dword.equalsIgnoreCase(String(wchars))  
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 detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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   σf2 = σa2 + σb2 Multiplication/Division If   f = ca   or   f = ac       then   σf = |cσa| If   f = ab   or   f = a / b   then   σf2 = f2( (σa / a)2 + (σb / b)2) Exponentiation If   f = ac   then   σf = |fc(σa / a)| Caution: This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   a   and   b   are independent and so the formula for multiplication should not be applied to   a*a   for example.   See   the talk page   for some of the implications of this issue. Task details Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. Given coordinates and their errors: x1 = 100 ± 1.1 y1 = 50 ± 1.2 x2 = 200 ± 2.2 y2 = 100 ± 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = √   (x1 - x2)²   +   (y1 - y2)²   Print and display both   d   and its error. References A Guide to Error Propagation B. Keeney, 2005. Propagation of uncertainty Wikipedia. Related task   Quaternion type
#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[VALUE] + b[VALUE], delta} return ret end function function imprecise_mul(imprecise a, b) atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA])) imprecise ret = {a[VALUE] * b[VALUE],delta} return ret end function function imprecise_div(imprecise a, b) atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA]))/sqr(b[VALUE]) imprecise ret = {a[VALUE] / b[VALUE], delta} return ret end function function imprecise_pow(imprecise a, atom c) atom v = power(a[VALUE], c), delta = abs(v*c*a[DELTA]/a[VALUE]) imprecise ret = {v,delta} return ret end function function printImprecise(imprecise imp) return sprintf("%g+/-%g",imp) end function imprecise x1 = {100, 1.1}, y1 = {50, 1.2}, x2 = {-200, 2.2}, y2 = {-100, 2.3}, tmp1, tmp2, d tmp1 = imprecise_add(x1, x2) tmp1 = imprecise_pow(tmp1, 2) tmp2 = imprecise_add(y1, y2) tmp2 = imprecise_pow(tmp2, 2) d = imprecise_add(tmp1,tmp2) d = imprecise_pow(d, 0.5) printf(1,"Distance, d, between the following points :") printf(1,"\n( x1, y1) = ( %s, %s)",{printImprecise(x1),printImprecise(y1)}) printf(1,"\n( x2, y2) = ( %s, %s)",{printImprecise(x2),printImprecise(y2)}) printf(1,"\nis d = %s\n", {printImprecise(d)})
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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) { } } \\ make f closure by reference m->ref(false) =lambda$ m->{ if m=>f then exit r$=Key$ m=>f=r$="." =r$ } \\ exit function break } name$=tempname$ \\ we use Ansi type files Open name$ for output as F Print #F, buf$; Close #F Open name$ for input as #f class ref { f class: module ref (.f) { } } \\ make f closure by reference m->ref(f) =lambda$ m -> { if m=>f=-1000 then exit def r$ if not eof(#m=>f) then r$=Input$(#m=>f,2) =r$ if r$="" or r$="." then close #m=>f : m=>f=-1000 } } Module Odd(c$) { one$="" Module MyEven(c$, &last$) { one$=If$(last$=""->c$(), last$) if one$="" then exit if not one$ ~"[a-zA-Z]" Then last$=one$: exit \\ print before Print one$; out$<=one$ Call MyEven, c$, &last$ } Module MyOdd(c$, &last$) { one$=If$(last$=""->c$(), last$) if one$="" then exit if not one$ ~"[a-zA-Z]" Then last$=one$: exit Call MyOdd, c$, &last$ \\ print after Print one$; out$<=one$ } Do { one$="" Call MyEven, c$, &one$ if one$="" then exit Print one$; out$<=one$ one$="" Call MyOdd, c$, &one$ if one$="" then exit Print one$; out$<=one$ } Always Print out$<={ } } \\ Feeding keyboard keyboard "what,is,the;meaning,of:life." Odd PrepareStream$("") \\ Use a file for input Odd PrepareStream$("we,are;not,in,kansas;any,more.") clipboard out$ } Checkit  
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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 proc clos(): bool = stdout.write(a) prev()   return odd(clos)   proc even(): bool = while true: let c = stdin.readChar() stdout.write(c) if not isAlpha(Rune(ord(c))): return c != '.'   var e = false while (if e: odd() else: even()): e = not e
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, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#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(n, minus,str) { if (n < 0) { n = n * -1 minus = "minus " } if (n == 0) { str = "zero" } else { str = intowords(n) } gsub(/ /," ",str) gsub(/ $/,"",str) return(minus str) } function intowords(n) { n = int(n) if (n >= 1000000000000) { return intowords(n/1000000000000) " trillion " intowords(n%1000000000000) } if (n >= 1000000000) { return intowords(n/1000000000) " billion " intowords(n%1000000000) } if (n >= 1000000) { return intowords(n/1000000) " million " intowords(n%1000000) } if (n >= 1000) { return intowords(n/1000) " thousand " intowords(n%1000) } if (n >= 100) { return intowords(n/100) " hundred " intowords(n%100) } if (n >= 20) { return tens[int(n/10)] " " intowords(n%10) } return(nums[n]) } function init_numtowords() { split("one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen",nums," ") split("ten twenty thirty forty fifty sixty seventy eighty ninety",tens," ") }  
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 reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#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: tries% = 0 REPEAT tries% += 1 FOR i% = 0 TO 8 : PRINT ; list%(i%) " " ; : NEXT INPUT ": Reverse how many", n% PROCreverse(list%(), n%) test%() = list%() - done%() UNTIL MOD(test%()) = 0 PRINT "You took " ; tries% " attempts." END   DEF PROCreverse(a%(), n%) IF n% < 2 ENDPROC LOCAL i% n% -= 1 FOR i% = 0 TO n% DIV 2 SWAP a%(i%), a%(n%-i%) NEXT ENDPROC
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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#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)))))   (defun next-cycle (value) (let ((new-value (make-array (length value) :element-type 'bit))) (loop for i below (length value) do (setf (bit new-value i) (if (= 2 (count-neighbors-and-self value i)) 1 0))) new-value))   (defun print-world (value &optional (stream *standard-output*)) (loop for i below (length value) do (princ (if (zerop (bit value i)) #\. #\#) stream)) (terpri stream))
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 that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#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 + h / 2); end;   function RectRight(f: TFx; x, h: Double): Double; begin Result := f(x + h); end;   function Trapezium(f: TFx; x, h: Double): Double; begin Result := (f(x) + f(x + h)) / 2.0; end;   function Simpson(f: TFx; x, h: Double): Double; begin Result := (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6.0; end;   function Integrate(Method: TMethod; f: TFx; a, b: Double; n: Integer): Double; var h: Double; k: integer; begin Result := 0; h := (b - a) / n; for k := 0 to n - 1 do Result := Result + Method(f, a + k * h, h); Result := Result * h; end;   function f1(x: Double): Double; begin Result := x * x * x; end;   function f2(x: Double): Double; begin Result := 1 / x; end;   function f3(x: Double): Double; begin Result := x; end;   var fs: array[0..3] of TFx; mt: array[0..4] of TMethod; fsNames: array of string = ['x^3', '1/x', 'x', 'x']; mtNames: array of string = ['RectLeft', 'RectMid', 'RectRight', 'Trapezium', 'Simpson']; limits: array of array of Double = [[0, 1, 100], [1, 100, 1000], [0, 5000, 5000000], [0, 6000, 6000000]]; i, j, n: integer; a, b: double;   begin fs[0] := f1; fs[1] := f2; fs[2] := f3; fs[3] := f3;   mt[0] := RectLeft; mt[1] := RectMid; mt[2] := RectRight; mt[3] := Trapezium; mt[4] := Simpson;   for i := 0 to High(fs) do begin Writeln('Integrate ' + fsNames[i]); a := limits[i][0]; b := limits[i][1]; n := Trunc(limits[i][2]);   for j := 0 to High(mt) do Writeln(Format('%.6f', [Integrate(mt[j], fs[i], a, b, n)])); end; readln; end.
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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) { falls = falls + 1 } } prev = d n = (n/10).floor } return rises == falls }   System.print("The first 200 numbers in the sequence are:") var count = 0 var n = 1 while (true) { if (risesEqualsFalls.call(n)) { count = count + 1 if (count <= 200) { Fmt.write("$3d ", n) if (count % 20 == 0) System.print() } if (count == 1e7) { Fmt.print("\nThe 10 millionth number in the sequence is $,d.", n) break } } n = n + 1 }
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   d(i)  >  d(i+1) Examples   The number   726,169   has   3   rises and   2   falls,   so it isn't in the sequence.   The number     83,548   has   2   rises and   2   falls,   so it   is   in the sequence. Task   Print the first   200   numbers in the sequence   Show that the   10 millionth   (10,000,000th)   number in the sequence is   41,909,002 See also   OEIS Sequence  A296712   describes numbers whose digit sequence in base 10 have equal "rises" and "falls". Related tasks   Esthetic numbers
#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) then [Cnt:= Cnt+1; if Cnt <= 200 then [IntOut(0, N); if rem (Cnt/10) = 0 then CrLf(0) else ChOut(0, 9\tab\); ]; if Cnt = 10_000_000 then [Text(0, "10 millionth number is "); IntOut(0, N); CrLf(0); quit; ]; ]; N:= N+1; ]; ]
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 W(x)} . ∫ − 1 1 f ( x ) d x = ∫ − 1 1 W ( x ) g ( x ) d x {\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx} Those are then approximated by a sum of function values at specified points x i {\displaystyle x_{i}} multiplied by some weights w i {\displaystyle w_{i}} : ∫ − 1 1 W ( x ) g ( x ) d x ≈ ∑ i = 1 n w i g ( x i ) {\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})} In the case of Gauss-Legendre quadrature, the weighting function W ( x ) = 1 {\displaystyle W(x)=1} , so we can approximate an integral of f ( x ) {\displaystyle f(x)} with: ∫ − 1 1 f ( x ) d x ≈ ∑ i = 1 n w i f ( x i ) {\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})} For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods. The n {\displaystyle n} evaluation points x i {\displaystyle x_{i}} for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials P n ( x ) {\displaystyle P_{n}(x)} . Legendre polynomials are defined by the following recursive rule: P 0 ( x ) = 1 {\displaystyle P_{0}(x)=1} P 1 ( x ) = x {\displaystyle P_{1}(x)=x} n P n ( x ) = ( 2 n − 1 ) x P n − 1 ( x ) − ( n − 1 ) P n − 2 ( x ) {\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)} There is also a recursive equation for their derivative: P n ′ ( x ) = n x 2 − 1 ( x P n ( x ) − P n − 1 ( x ) ) {\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)} The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration: x n + 1 = x n − f ( x n ) f ′ ( x n ) {\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}} The first guess x 0 {\displaystyle x_{0}} for the i {\displaystyle i} -th root of a n {\displaystyle n} -order polynomial P n {\displaystyle P_{n}} can be given by x 0 = cos ⁡ ( π i − 1 4 n + 1 2 ) {\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)} After we get the nodes x i {\displaystyle x_{i}} , we compute the appropriate weights by: w i = 2 ( 1 − x i 2 ) [ P n ′ ( x i ) ] 2 {\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}} After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval [ a , b ] {\displaystyle [a,b]} by ∫ a b f ( x ) d x ≈ b − a 2 ∑ i = 1 n w i f ( b − a 2 x i + a + b 2 ) {\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)} Task description Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function f ( x ) {\displaystyle f(x)} , but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison. To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute: ∫ − 3 3 exp ⁡ ( x ) d x ≈ ∑ i = 1 5 w i exp ⁡ ( x i ) ≈ 20.036 {\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
#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], w: u[2], c: bfloat((a + b)/2), h: bfloat((b - a)/2), h*sum(w[i]*bfloat(f(c + x[i]*h)), i, 1, n))$     fpprec: 40$     gauss_int(lambda([x], 4/(1 + x^2)), 0, 1, 20); /* 3.141592653589793238462643379852215927697b0 */   % - bfloat(%pi); /* -3.427286956499858315999116083264403489053b-27 */     gauss_int(exp, -3, 3, 5); /* 2.003557771838556215392853572527509393154b1 */   % - bfloat(integrate(exp(x), x, -3, 3)); /* -1.721364342416440206515136565621888185351b-4 */
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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("\"", "")) }   serialize(fileName) { var o = JSON.parse(this.toString) File.openWithFlags(fileName, FileFlags.writeOnly) { |file| file.writeBytes("%(o)\n") } } }   class Person is Entity { construct new(name, age) { super(name) _age = age }   // JSON representation toString { "{\"name\": \"%(name)\", \"age\": \"%(_age)\"}" }   // mimics the JSON output print() { System.print(this.toString.replace("\"", "")) }   serialize(fileName) { var o = JSON.parse(this.toString) File.openWithFlags(fileName, FileFlags.writeOnly) { |file| file.writeBytes("%(o)\n") } } }   // create file for serialization var fileName = "objects.dat" var file = File.create(fileName) file.close()   System.print("Calling print methods gives:")   var e = Entity.new("John") e.print() e.serialize(fileName)   var p = Person.new("Fred", 35) p.print() p.serialize(fileName)   System.print("\nContents of objects.dat are:") System.print(File.read(fileName))
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 string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 swallow a dog." , "goat.\t\nShe just opened her throat and swallowed a goat." , "cow.\nI don't know how she swallowed a cow." , "horse.\nShe's dead, of course." ]   beginnings :: [String] beginnings = ("There was an old lady who swallowed a " ++) <$> animals   lastVerse :: [String] lastVerse = reverse [ "She swallowed the " ++ takeWhile (/= '.') y ++ " to catch the " ++ takeWhile (/= '\t') x | (x:y:_:_) <- tails animals ]   main :: IO () main = putStr $ concatMap unlines $ zipWith (:) beginnings $ reverse $ ([] :) (tails lastVerse)
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_BUFFER_BIT _glBegin _GL_TRIANGLES _glColor4f 1, 0, 0, 1 _glVertex2f -1, -1 _glColor4f 0, 1, 0, 1 _glVertex2f 0, 0 _glColor4f 0, 0, 1, 1 _glVertex2f 1, -1 _glEnd End Sub  
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 make it the possible choice if a uniform random value between zero and one is less than 1/2. Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ... Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N Return the computed possible choice when no further lines exist in the file. Task Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
#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 Result := 0; for i := low(a) to high(a) do Result := Result + a[i]; end;   const num_reps = 1000000; num_lines_in_file = 10;   var lines: array[1..num_reps] of longint; i: longint;   begin randomize; for i := 1 to num_reps do lines[i] := 0; for i := 1 to num_reps do inc(lines[one_of_n(num_lines_in_file)]); for i := 1 to num_lines_in_file do writeln('Number of times line ', i, ' was selected: ', lines[i]); writeln('Total number selected: ', sum(lines)); end.
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 An integer specifying which string of each row to compare; the first by default. reverse Reverses the ordering. This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both. Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment). See also: Named Arguments
#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"], ];   say table_sort(table, column: 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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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 Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. The order is determined by lexicographic order: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
#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("%w @< %w: %w\n",L1,L2,cond(L1 @< L2,true,false)) end, nl.
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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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.setLen(0) mx = word.len words.add word echo words.join(" ")
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 downloaded this file yourself.) The display needs to be shown on this page. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 String.iter (fun c -> lst := c :: !lst) str; (List.rev !lst)   let is_ordered word = let rec aux = function | c1::c2::tl -> if c1 <= c2 then aux (c2::tl) else false | c::[] -> true | [] -> true (* should only occur with an empty string *) in aux (char_list_of_string word)   let longest_words words = let res, _ = List.fold_left (fun (lst, n) word -> let len = String.length word in let comp = compare len n in match lst, comp with | lst, 0 -> ((word::lst), n) (* len = n *) | lst, -1 -> (lst, n) (* len < n *) | _, 1 -> ([word], len) (* len > n *) | _ -> assert false ) ([""], 0) words in (List.rev res)   let () = let ic = open_in "unixdict.txt" in let words = read_lines ic in let lower_words = List.map String.lowercase words in let ordered_words = List.filter is_ordered lower_words in let longest_ordered_words = longest_words ordered_words in List.iter print_endline longest_ordered_words
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 detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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   σf2 = σa2 + σb2 Multiplication/Division If   f = ca   or   f = ac       then   σf = |cσa| If   f = ab   or   f = a / b   then   σf2 = f2( (σa / a)2 + (σb / b)2) Exponentiation If   f = ac   then   σf = |fc(σa / a)| Caution: This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   a   and   b   are independent and so the formula for multiplication should not be applied to   a*a   for example.   See   the talk page   for some of the implications of this issue. Task details Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. Given coordinates and their errors: x1 = 100 ± 1.1 y1 = 50 ± 1.2 x2 = 200 ± 2.2 y2 = 100 ± 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = √   (x1 - x2)²   +   (y1 - y2)²   Print and display both   d   and its error. References A Guide to Error Propagation B. Keeney, 2005. Propagation of uncertainty Wikipedia. Related task   Quaternion type
#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 + a (cons (+ (car R) N) (cdr R)) # a + c (cons # a + b (+ (car R) (car N)) (+ (cdr R) (cdr N)) ) ) ) ) ) R ) )   (redef - @ (let R (next) (ifn (args) (- R) (while (args) (let N (next) (setq R (if2 (atom R) (atom N) (- R N) # c - c (cons (- R (car N)) (cdr N)) # c - a (cons (- (car R) N) (cdr R)) # a - c (cons # a - b (- (car R) (car N)) (+ (cdr R) (cdr N)) ) ) ) ) ) R ) ) )   (redef * @ (let R (next) (while (args) (let N (next) (setq R (if2 (atom R) (atom N) (* R N) # c * c (cons # c * a (*/ R (car N) 1.0) (mul2div2 (cdr N) R 1.0) ) (cons # a * c (*/ (car R) N 1.0) (mul2div2 (cdr R) N 1.0) ) (uncMul (*/ (car R) (car N) 1.0) R N) ) ) ) ) # a * b R ) )   (redef / @ (let R (next) (while (args) (let N (next) (setq R (if2 (atom R) (atom N) (/ R N) # c / c (cons # c / a (*/ R 1.0 (car N)) (mul2div2 (cdr N) R 1.0) ) (cons # a / c (*/ (car R) 1.0 N) (mul2div2 (cdr R) N 1.0) ) (uncMul (*/ (car R) 1.0 (car N)) R N) ) ) ) ) # a / b R ) )   (redef ** (A C) (if (atom A) (** A C) (let F (pow (car A) C) (cons F (mul2div2 (cdr A) (*/ F C (car A)) 1.0) ) ) ) )   # Utilities (de mul2div2 (A B C) (*/ A B B (* C C)) )   (de uncMul (F R N) (cons F (mul2div2 (+ (mul2div2 (cdr R) 1.0 (car R)) (mul2div2 (cdr N) 1.0 (car N)) ) F 1.0 ) ) )   # I/O conversion (de unc (N U) (if U (cons N (*/ U U 1.0)) (pack (round (car N) 10) " ± " (round (sqrt (cdr N) 1.0) 8) ) ) )
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   σf2 = σa2 + σb2 Multiplication/Division If   f = ca   or   f = ac       then   σf = |cσa| If   f = ab   or   f = a / b   then   σf2 = f2( (σa / a)2 + (σb / b)2) Exponentiation If   f = ac   then   σf = |fc(σa / a)| Caution: This implementation of error propagation does not address issues of dependent and independent values.   It is assumed that   a   and   b   are independent and so the formula for multiplication should not be applied to   a*a   for example.   See   the talk page   for some of the implications of this issue. Task details Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. Given coordinates and their errors: x1 = 100 ± 1.1 y1 = 50 ± 1.2 x2 = 200 ± 2.2 y2 = 100 ± 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = √   (x1 - x2)²   +   (y1 - y2)²   Print and display both   d   and its error. References A Guide to Error Propagation B. Keeney, 2005. Propagation of uncertainty Wikipedia. Related task   Quaternion type
#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)))   def reciprocal(self): return I(1. / self.value, self.delta / (self.value**2))   def __str__(self): 'Shorter form of Imprecise as string' return 'I(%g, %g)' % self   def __neg__(self): return I(-self.value, self.delta)   def __add__(self, other): if type(other) == I: return I( self.value + other.value, (self.delta**2 + other.delta**2)**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value + c, self.delta)   def __sub__(self, other): return self + (-other)   def __radd__(self, other): return I.__add__(self, other)   def __mul__(self, other): if type(other) == I: #if id(self) == id(other): # return self ** 2 a1,b1 = self a2,b2 = other f = a1 * a2 return I( f, f * ( (b1 / a1)**2 + (b2 / a2)**2 )**0.5 ) try: c = float(other) except: return NotImplemented return I(self.value * c, self.delta * c)   def __pow__(self, other): if type(other) == I: return NotImplemented try: c = float(other) except: return NotImplemented f = self.value ** c return I(f, f * c * (self.delta / self.value))   def __rmul__(self, other): return I.__mul__(self, other)   def __truediv__(self, other): if type(other) == I: return self.__mul__(other.reciprocal()) try: c = float(other) except: return NotImplemented return I(self.value / c, self.delta / c)   def __rtruediv__(self, other): return other * self.reciprocal()   __div__, __rdiv__ = __truediv__, __rtruediv__   Imprecise = I   def distance(p1, p2): x1, y1 = p1 x2, y2 = p2 return ((x1 - x2)**2 + (y1 - y2)**2)**0.5   x1 = I(100, 1.1) x2 = I(200, 2.2) y1 = I( 50, 1.2) y2 = I(100, 2.3)   p1, p2 = (x1, y1), (x2, y2) print("Distance between points\n p1: %s\n and p2: %s\n = %r" % ( p1, p2, distance(p1, p2)))
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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_words () = while true do even (); print_char (odd ()) done   let () = try rev_odd_words () with End_of_file -> ()
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 begin with a word, the words will be at least one letter long,   and a full stop (a period, [.]) appears after, and only after, the last word. Example A stream with six words: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: what,si,the;gninaem,of:efil. while observing the following restrictions: Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. Test cases Work on both the   "life"   example given above, and also the text: we,are;not,in,kansas;any,more.
#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) (cons (car s) l)) (even (cdr s) (cons (cons (reverse l) (car s)) out)))) (else (loop (s) l)))))) (even (lambda (s out) (let loop ((s s) (l '())) (cond ((null? s) out) ((pair? s) (if (<= #\a (car s) #\z) (loop (cdr s) (cons (car s) l)) (odd (cdr s) (cons (cons l (car s)) out)))) (else (loop (s) l))))))) (for-each (lambda (p) (display (runes->string (car p))) (display (string (cdr p)))) (reverse (odd (str-iter words) '())))) (print)) (odd_word_problem "what,is,the;meaning,of:life.") (odd_word_problem "we,are;not,in,kansas;any,more.")  
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, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#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", "ninety" 'big DATA "thousand", "million", "billion"   DIM SHARED small(1 TO 19) AS STRING, tens(7) AS STRING, big(2) AS STRING   DIM tmpInt AS INTEGER   FOR tmpInt = 1 TO 19 READ small(tmpInt) NEXT FOR tmpInt = 0 TO 7 READ tens(tmpInt) NEXT FOR tmpInt = 0 TO 2 READ big(tmpInt) NEXT     DIM n AS LONG   INPUT "Gimme a number! ", n PRINT int2Text$(n)   FUNCTION int2Text$ (number AS LONG) DIM num AS LONG, outP AS STRING, unit AS INTEGER DIM tmpLng1 AS LONG   IF 0 = number THEN int2Text$ = "zero" EXIT FUNCTION END IF   num = ABS(number)   DO tmpLng1 = num MOD 100 SELECT CASE tmpLng1 CASE 1 TO 19 outP = small(tmpLng1) + " " + outP CASE 20 TO 99 SELECT CASE tmpLng1 MOD 10 CASE 0 outP = tens((tmpLng1 \ 10) - 2) + " " + outP CASE ELSE outP = tens((tmpLng1 \ 10) - 2) + "-" + small(tmpLng1 MOD 10) + " " + outP END SELECT END SELECT   tmpLng1 = (num MOD 1000) \ 100 IF tmpLng1 THEN outP = small(tmpLng1) + " hundred " + outP END IF   num = num \ 1000 IF num < 1 THEN EXIT DO   tmpLng1 = num MOD 1000 IF tmpLng1 THEN outP = big(unit) + " " + outP   unit = unit + 1 LOOP   IF number < 0 THEN outP = "negative " + outP   int2Text$ = RTRIM$(outP) END FUNCTION
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 reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#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 + numbers[num, length] turns = turns + 1 }   p numbers p "It took #{turns} turns to sort numbers."
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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#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 *> and expect void return (callee returning omitted) *> and do not touch default return-code (returning nothing) procedure division. call "test-null" using thing-not-thing omitted returning nothing goback. end program null-objects.   *> Test for pointer to null (still a real thing that takes space) *> and an omitted parameter, (call frame has placeholder) *> and finally, return void, (omitted) identification division. program-id. test-null.   data division. linkage section. 01 thing-one usage pointer. 01 thing-two pic x.   procedure division using thing-one optional thing-two returning omitted.   if thing-one equal null then display "thing-one pointer to null" upon syserr end-if   if thing-two omitted then display "no thing-two was passed" upon syserr end-if goback. end program test-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 following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#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) { write(A[i] == '0' ? '_' : '#'); const val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0'); B[i] = table[val]; } A.swap(B); writeln; } }
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 that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#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, b, steps, meth) { def h := (b-a) / steps return h * accum 0 for i in 0..!steps { _ + meth(f, a+i*h, h) } }
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 W(x)} . ∫ − 1 1 f ( x ) d x = ∫ − 1 1 W ( x ) g ( x ) d x {\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx} Those are then approximated by a sum of function values at specified points x i {\displaystyle x_{i}} multiplied by some weights w i {\displaystyle w_{i}} : ∫ − 1 1 W ( x ) g ( x ) d x ≈ ∑ i = 1 n w i g ( x i ) {\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})} In the case of Gauss-Legendre quadrature, the weighting function W ( x ) = 1 {\displaystyle W(x)=1} , so we can approximate an integral of f ( x ) {\displaystyle f(x)} with: ∫ − 1 1 f ( x ) d x ≈ ∑ i = 1 n w i f ( x i ) {\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})} For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods. The n {\displaystyle n} evaluation points x i {\displaystyle x_{i}} for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials P n ( x ) {\displaystyle P_{n}(x)} . Legendre polynomials are defined by the following recursive rule: P 0 ( x ) = 1 {\displaystyle P_{0}(x)=1} P 1 ( x ) = x {\displaystyle P_{1}(x)=x} n P n ( x ) = ( 2 n − 1 ) x P n − 1 ( x ) − ( n − 1 ) P n − 2 ( x ) {\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)} There is also a recursive equation for their derivative: P n ′ ( x ) = n x 2 − 1 ( x P n ( x ) − P n − 1 ( x ) ) {\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)} The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration: x n + 1 = x n − f ( x n ) f ′ ( x n ) {\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}} The first guess x 0 {\displaystyle x_{0}} for the i {\displaystyle i} -th root of a n {\displaystyle n} -order polynomial P n {\displaystyle P_{n}} can be given by x 0 = cos ⁡ ( π i − 1 4 n + 1 2 ) {\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)} After we get the nodes x i {\displaystyle x_{i}} , we compute the appropriate weights by: w i = 2 ( 1 − x i 2 ) [ P n ′ ( x i ) ] 2 {\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}} After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval [ a , b ] {\displaystyle [a,b]} by ∫ a b f ( x ) d x ≈ b − a 2 ∑ i = 1 n w i f ( b − a 2 x i + a + b 2 ) {\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)} Task description Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function f ( x ) {\displaystyle f(x)} , but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison. To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute: ∫ − 3 3 exp ⁡ ( x ) d x ≈ ∑ i = 1 5 w i exp ⁡ ( x i ) ≈ 20.036 {\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
#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 p2 = 1.0 for i in 2 .. n: result = (i.prev1(p1) - i.prev2(p2)) / i.float p2 = p1 p1 = result   proc deriveLegendreIn(x: float, n: int): float = template calcresult(curr, prev: float): untyped = n.float / (x^2 - 1) * (x * curr - prev) result = calcresult(x.legendreIn n, x.legendreIn(n-1))   func guess(n, i: int): float = cos(PI * (i.float - 0.25) / (n.float + 0.5))   proc nodes(n: int): seq[(float, float)] = result = newseq[(float, float)](n) template calc(x: float): untyped = x.legendreIn(n) / x.deriveLegendreIn(n)   for i in 0 .. result.high: var x = guess(n, i+1) block newton: var x0 = x x -= calc x while abs(x-x0) > 1e-12: x0 = x x -= calc x   result[i][0] = x result[i][1] = 2 / ((1.0 - x^2) * (x.deriveLegendreIn n)^2)   proc integ(f: proc(x: float): float; ns, p1, p2: int): float = template dist: untyped = (p2 - p1).float / 2.0 template avg: untyped = (p1 + p2).float / 2.0 result = dist() var sum = 0'f thenodes = newseq[float](ns) weights = newseq[float](ns) for i, nw in ns.nodes: sum += nw[1] * f(dist() * nw[0] + avg()) thenodes[i] = nw[0] weights[i] = nw[1]   let apos = ":" stdout.write fmt"""{"nodes":>8}{apos}""" for n in thenodes: stdout.write &" {n:>6.5f}" stdout.write "\n" stdout.write &"""{"weights":>8}{apos}""" for w in weights: stdout.write &" {w:>6.5f}" stdout.write "\n" result *= sum   proc main = echo "integral: ", integ(exp, 5, -3, 3)   main()  
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 objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
#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) constructor x is 456   f:=File("object.dat","wb"); Compiler.Asm.writeRootClass(ARootClass,f); // serialize to file f.close();   f:=File("object.dat","rb"); rc:=Compiler.Asm.readRootClass(f); // read and re-create // prints (readRootClass calls all constructors by default): Class(A) constructor f.close(); rc.B().println(); // create a new instance of B // prints: x is 123