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/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
#Haskell
Haskell
  -- Words are read from the standard input. We keep in memory only the current -- set of longest, ordered words. -- -- Limitation: the locale's collation order is not take into consideration.   isOrdered wws@(_:ws) = and $ zipWith (<=) wws ws   longestOrderedWords = reverse . snd . foldl f (0,[]) . filter isOrdered where f (max, acc) w = let len = length w in case compare len max of LT -> (max, acc) EQ -> (max, w:acc) GT -> (len, [w])   main = do str <- getContents let ws = longestOrderedWords $ words str mapM_ putStrLn ws  
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
#Picat
Picat
go => Tests = ["In girum imus nocte et consumimur igni", "this is a non palindrome string", "anna ABcdcBA anna", "anna ABcdcBA annax", "A man, a plan, a canoe, pasta, heros, rajahs" ++ "a coloratura, maps, snipe, percale, macaroni, " ++ "a gag, a banana bag, a tan, a tag, " ++ "a banana bag again (or a camel), a crepe, pins, " ++ "Spam, a rut, a Rolo, cash, a jar, sore hats, " ++ "a peon, a canal - Panama!", 10, 111111, 12221, 9384212, 10.01 ],   foreach(Test in Tests) if is_palindrome(Test) then println([Test, "exact palindrome"]) elseif is_palindrome_inexact(Test) then println([Test, "inexact palindrome"]) else println([Test, "no"]) end end, nl.   % Detect palindromes for strings (and numbers). is_palindrome(N), number(N) => is_palindrome(N.to_string()). is_palindrome(S) => S == S.reverse().   % Detect inexact palindromes. is_palindrome_inexact(N), number(N) => is_palindrome_inexact(N.to_string()). is_palindrome_inexact(S) => is_palindrome(strip(S)).     % convert to lowercase and % skips punctuation and white space. strip(S) = [C : C in S.to_lowercase(), not C.membchk("!?,.;-_ \t\n()[]{}")].
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
#C.2B.2B
C++
#pragma once   #include <cmath> #include <string> #include <sstream> #include <iomanip>   class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}   operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); }   Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); }   Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); }   Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }   Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); }   Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }   Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); }   private: double v, s; };
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares
Numbers which are not the sum of distinct squares
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. 1 == 1 5 == 4 + 1 25 == 16 + 9 77 == 36 + 25 + 16 103 == 49 + 25 + 16 + 9 + 4 Many can be generated in multiple ways: 90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9 130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9 The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite: 2, 3, 6, 7, etc. Task Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares. Do not use magic numbers or pre-determined limits. Justify your answer mathematically. See also OEIS: A001422 Numbers which are not the sum of distinct squares
#Phix
Phix
with javascript_semantics sequence summable = {true} -- (1 can be expressed as 1*1) integer n = 2 while true do integer sq = n*n summable &= repeat(false,sq) -- (process backwards to avoid adding sq more than once) for i=length(summable)-sq to 1 by -1 do if summable[i] then summable[i+sq] = true end if end for summable[sq] = true integer r = match(repeat(true,(n+1)*(n+1)),summable) if r then summable = summable[1..r-1] exit end if n += 1 end while constant nwansods = "numbers which are not the sum of distinct squares" printf(1,"%s\n",{join(shorten(apply(find_all(false,summable),sprint),nwansods,5))})
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares
Numbers which are not the sum of distinct squares
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. 1 == 1 5 == 4 + 1 25 == 16 + 9 77 == 36 + 25 + 16 103 == 49 + 25 + 16 + 9 + 4 Many can be generated in multiple ways: 90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9 130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9 The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite: 2, 3, 6, 7, etc. Task Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares. Do not use magic numbers or pre-determined limits. Justify your answer mathematically. See also OEIS: A001422 Numbers which are not the sum of distinct squares
#Raku
Raku
my @squares = ^∞ .map: *²; # Infinite series of squares   for 1..∞ -> $sq { # for every combination of all squares my @sums = @squares[^$sq].combinations».sum.unique.sort; my @run; for @sums { @run.push($_) and next unless @run.elems; if $_ == @run.tail + 1 { @run.push: $_ } else { last if @run.elems > @squares[$sq]; @run = () } } put grep * ∉ @sums, 1..@run.tail and last if @run.elems > @squares[$sq]; }
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.
#CoffeeScript
CoffeeScript
isWordChar = (c) -> /^\w/.test c isLastChar = (c) -> c is '.'   # Pass a function that returns an input character and one that outputs a # character. JS platforms' ideas of single-character I/O vary widely, but this # abstraction is adaptable to most or all. oddWord = (get, put) -> forwardWord = -> loop # No magic here; buffer then immediately output. c = get() put(c) unless isWordChar(c) return not isLastChar(c)   # NB: (->) is a CoffeeScript idiom for no-op. reverseWord = (outputPending = (->)) -> c = get() if isWordChar(c) # Continue word. # Tell recursive call to output this character, then any previously # pending characters, after the next word character, if any, has # been output. reverseWord -> put(c) outputPending() else # Word is done. # Output previously pending characters, then this punctuation. outputPending() put(c) return not isLastChar(c)   # Alternate between forward and reverse until one or the other reports that # the end-of-input mark has been reached (causing a return of false). continue while forwardWord() and reverseWord()
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.
#Common_Lisp
Common Lisp
(defun odd-word (s) (let ((stream (make-string-input-stream s))) (loop for forwardp = t then (not forwardp) while (if forwardp (forward stream) (funcall (backward stream)))) ))   (defun forward (stream) (let ((ch (read-char stream))) (write-char ch) (if (alpha-char-p ch) (forward stream) (char/= ch #\.))))   (defun backward (stream) (let ((ch (read-char stream))) (if (alpha-char-p ch) (prog1 (backward stream) (write-char ch)) #'(lambda () (write-char ch) (char/= ch #\.)))) )  
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.
#AutoHotkey
AutoHotkey
n := 22, n1 := n+1, v0 := v%n1% := 0 ; set grid dimensions, and fixed cells   Loop % n { ; draw a line of checkboxes v%A_Index% := 0 Gui Add, CheckBox, % "y10 w17 h17 gCheck x" A_Index*17-5 " vv" A_Index } Gui Add, Button, x+5 y6, step ; button to step to next generation Gui Show Return   Check: GuiControlGet %A_GuiControl% ; set cells by the mouse Return   ButtonStep: ; move to next generation Loop % n i := A_Index-1, j := i+2, w%A_Index% := v%i%+v%A_Index%+v%j% = 2 Loop % n GuiControl,,v%A_Index%, % v%A_Index% := w%A_Index% Return   GuiClose: ; exit when GUI is closed ExitApp
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.
#Ada
Ada
generic type Scalar is digits <>; with function F (X : Scalar) return Scalar; package Integrate is function Left_Rectangular (A, B : Scalar; N : Positive) return Scalar; function Right_Rectangular (A, B : Scalar; N : Positive) return Scalar; function Midpoint_Rectangular (A, B : Scalar; N : Positive) return Scalar; function Trapezium (A, B : Scalar; N : Positive) return Scalar; function Simpsons (A, B : Scalar; N : Positive) return Scalar; end Integrate;
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
#Ada
Ada
with Ada.Text_Io; with Ada.Integer_Text_Io;   procedure Equal_Rise_Fall is use Ada.Text_Io;   function Has_Equal_Rise_Fall (Value : Natural) return Boolean is Rises : Natural := 0; Falls : Natural := 0; Image : constant String := Natural'Image (Value); Last  : Character := Image (Image'First + 1); begin for Pos in Image'First + 2 .. Image'Last loop if Image (Pos) > Last then Rises := Rises + 1; elsif Image (Pos) < Last then Falls := Falls + 1; end if; Last := Image (Pos); end loop; return Rises = Falls; end Has_Equal_Rise_Fall;   Value : Natural := 1; Count : Natural := 0; begin loop if Has_Equal_Rise_Fall (Value) then Count := Count + 1; if Count <= 200 then Ada.Integer_Text_Io.Put (Value, Width => 5); if Count mod 20 = 0 then New_Line; end if; end if; if Count = 10_000_000 then New_Line; Put_Line ("The 10_000_000th: " & Natural'Image (Value)); exit; end if; end if; Value := Value + 1; end loop; end Equal_Rise_Fall;
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
#ALGOL_68
ALGOL 68
BEGIN # returns TRUE if the number of digits in n followed by a higher digit (rises) # # equals the number of digits followed by a lower digit (falls) # # FALSE otherwise # PROC rises equals falls = ( INT n )BOOL: BEGIN INT rf := 0; INT prev := n MOD 10; INT v := n OVER 10; WHILE v > 0 DO INT d = v MOD 10; IF d < prev THEN rf +:= 1 # rise # ELIF d > prev THEN rf -:= 1 # fall # FI; prev := d; v OVERAB 10 OD; rf = 0 END; # rises equals falls # # task tests # print( ( "The first 200 numbers in the sequence are:", newline ) ); INT count := 0; INT max count = 10 000 000; FOR n WHILE count < max count DO IF rises equals falls( n ) THEN count +:= 1; IF count <= 200 THEN print( ( whole( n, -4 ) ) ); IF count MOD 20 = 0 THEN print( ( newline ) ) FI ELIF count = max count THEN print( ( newline, "The 10 millionth number in the sequence is ", whole( n, -8 ), ".", newline ) ) FI FI OD END  
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}
#Common_Lisp
Common Lisp
;; Computes the initial guess for the root i of a n-order Legendre polynomial. (defun guess (n i) (cos (* pi (/ (- i 0.25d0) (+ n 0.5d0)))))   ;; Computes and evaluates the n-order Legendre polynomial at the point x. (defun legpoly (n x) (let ((pa 1.0d0) (pb x) (pn)) (cond ((= n 0) pa) ((= n 1) pb) (t (loop for i from 2 to n do (setf pn (- (* (/ (- (* 2 i) 1) i) x pb) (* (/ (- i 1) i) pa))) (setf pa pb) (setf pb pn) finally (return pn))))))   ;; Computes and evaluates the derivative of an n-order Legendre polynomial at point x. (defun legdiff (n x) (* (/ n (- (* x x) 1)) (- (* x (legpoly n x)) (legpoly (- n 1) x))))   ;; Computes the n nodes for an n-point quadrature rule. (i.e. n roots of a n-order polynomial) (defun nodes (n) (let ((x (make-array n :initial-element 0.0d0))) (loop for i from 0 to (- n 1) do (let ((val (guess n (+ i 1))) ;Nullstellen-Schätzwert. (itermax 5)) (dotimes (j itermax) (setf val (- val (/ (legpoly n val) (legdiff n val))))) (setf (aref x i) val))) x))   ;; Computes the weight for an n-order polynomial at the point (node) x. (defun legwts (n x) (/ 2 (* (- 1 (* x x)) (expt (legdiff n x) 2))))   ;; Takes a array of nodes x and computes an array of corresponding weights w. (defun weights (x) (let* ((n (car (array-dimensions x))) (w (make-array n :initial-element 0.0d0))) (loop for i from 0 to (- n 1) do (setf (aref w i) (legwts n (aref x i)))) w))   ;; Integrates a function f with a n-point Gauss-Legendre quadrature rule over the interval [a,b]. (defun int (f n a b) (let* ((x (nodes n)) (w (weights x))) (* (/ (- b a) 2.0d0) (loop for i from 0 to (- n 1) sum (* (aref w i) (funcall f (+ (* (/ (- b a) 2.0d0) (aref x i)) (/ (+ a b) 2.0d0))))))))
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.
#Factor
Factor
USING: accessors combinators.extras io io.encodings.binary io.files io.files.info kernel prettyprint serialize ; IN: rosetta-code.object-serialization   ! Define two classes, item and armor. armor is a subclass of ! item.   TUPLE: item name value ; TUPLE: armor < item physical-resistance fire-resistance ;   ! Define boa constructors for both classes using C: shorthand. ! boa means By Order of Arguments, and yes, this is a pun on boa ! constrictors.   C: <item> item C: <armor> armor   ! Create three example items and print them out ! non-destructively.   "Fish scales" 0.05 <item> "Gold piece" 1 <item> "Breastplate of Ashannar" 50,000 55 30 <armor> [ [ . ] keep ] tri@ nl   ! Serialize the three objects to a binary file named ! objects.dat.   "Serializing objects to objects.dat . . . " print "objects.dat" binary [ [ serialize ] tri@ ] with-file-writer   ! Check that objects.dat exists.   "objects.dat exists? " write "objects.dat" exists? . "Size on disk: " write "objects.dat" file-info size>> pprint " bytes" print nl   ! Deserialize three objects from objects.dat.   "Deserializing objects from objects.dat . . . " print nl "objects.dat" binary [ [ deserialize ] thrice ] with-file-reader   ! Print out deserialized objects.   [ . ] tri@
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.
#Go
Go
package main   import ( "encoding/gob" "fmt" "os" )   type printable interface { print() }   func main() { // create instances animals := []printable{ &Animal{Alive: true}, &Cat{}, &Lab{ Dog: Dog{Animal: Animal{Alive: true}}, Color: "yellow", }, &Collie{Dog: Dog{ Animal: Animal{Alive: true}, ObedienceTrained: true, }}, }   // display fmt.Println("created:") for _, a := range animals { a.print() }   // serialize f, err := os.Create("objects.dat") if err != nil { fmt.Println(err) return } for _, a := range animals { gob.Register(a) } err = gob.NewEncoder(f).Encode(animals) if err != nil { fmt.Println(err) return } f.Close()   // read f, err = os.Open("objects.dat") if err != nil { fmt.Println(err) return } var clones []printable gob.NewDecoder(f).Decode(&clones) if err != nil { fmt.Println(err) return }   // display fmt.Println("\nloaded from objects.dat:") for _, c := range clones { c.print() } }   type Animal struct { Alive bool }   func (a *Animal) print() { if a.Alive { fmt.Println(" live animal, unspecified type") } else { fmt.Println(" dead animal, unspecified type") } }   type Dog struct { Animal ObedienceTrained bool }   func (d *Dog) print() { switch { case !d.Alive: fmt.Println(" dead dog") case d.ObedienceTrained: fmt.Println(" trained dog") default: fmt.Println(" dog, not trained") } }   type Cat struct { Animal LitterBoxTrained bool }   func (c *Cat) print() { switch { case !c.Alive: fmt.Println(" dead cat") case c.LitterBoxTrained: fmt.Println(" litter box trained cat") default: fmt.Println(" cat, not litter box trained") } }   type Lab struct { Dog Color string }   func (l *Lab) print() { var r string if l.Color == "" { r = "lab, color unspecified" } else { r = l.Color + " lab" } switch { case !l.Alive: fmt.Println(" dead", r) case l.ObedienceTrained: fmt.Println(" trained", r) default: fmt.Printf("  %s, not trained\n", r) } }   type Collie struct { Dog CatchesFrisbee bool }   func (c *Collie) print() { switch { case !c.Alive: fmt.Println(" dead collie") case c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" trained collie, catches frisbee") case c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" trained collie, but doesn't catch frisbee") case !c.ObedienceTrained && c.CatchesFrisbee: fmt.Println(" collie, not trained, but catches frisbee") case !c.ObedienceTrained && !c.CatchesFrisbee: fmt.Println(" collie, not trained, doesn't catch frisbee") } }
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
#BBC_BASIC
BBC BASIC
REM >oldlady DIM swallowings$(6, 1) swallowings$() = "fly", "+why", "spider", "That wriggled and wiggled and tickled inside her", "bird", ":How absurd", "cat", ":Fancy that", "dog", ":What a hog", "cow", "+how", "horse", "She's dead, of course" FOR i% = 0 TO 6 PRINT "There was an old lady who swallowed a "; swallowings$(i%, 0); "..." PROC_comment_on_swallowing(swallowings$(i%, 0), swallowings$(i%, 1)) IF i% > 0 AND i% < 6 THEN FOR j% = i% TO 1 STEP -1 PRINT "She swallowed the "; swallowings$(j%, 0); " to catch the "; swallowings$(j% - 1, 0); "," NEXT PROC_comment_on_swallowing(swallowings$(0, 0), swallowings$(0, 1)) ENDIF PRINT NEXT END : DEF PROC_comment_on_swallowing(animal$, observation$) CASE LEFT$(observation$, 1) OF WHEN "+": PRINT "I don't know "; MID$(observation$, 2); " she swallowed a "; animal$; IF animal$ = "fly" THEN PRINT " -- perhaps she'll die"; PRINT "!" WHEN ":" PRINT MID$(observation$, 2); ", to swallow a "; animal$; "!" OTHERWISE PRINT observation$; "!" ENDCASE ENDPROC
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
#BCPL
BCPL
get "libhdr"   let animal(n) = n=0 -> "fly", n=1 -> "spider", n=2 -> "bird", n=3 -> "cat", n=4 -> "dog", n=5 -> "goat", n=6 -> "cow", n=7 -> "horse", valof finish   let line(n) = n=0 -> "I don't know why she swallowed that fly,*NPerhaps she'll die.*N", n=1 -> "That wiggled and jiggled and tickled inside her", n=2 -> "How absurd to swallow a bird", n=3 -> "Imagine that, she swallowed a cat!", n=4 -> "What a hog to swallow a dog", n=5 -> "She just opened her throat and swallowed that goat", n=6 -> "I don't know how she swallowed that cow", n=7 -> "She's dead, of course.", valof finish   let verse(n) be $( writef("There was an old lady who swallowed a %S,*N", animal(n)) writef("%S*N", line(n))   unless n=7 for i=n to 1 by -1 $( writef("She swallowed the %S to catch the %S,*N", animal(i), animal(i-1)) if i <= 2 do writef("%S*N", line(i-1)) $) $)   let start() be for n=0 to 7 do verse(n)
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes
Numerical and alphabetical suffixes
This task is about expressing numbers with an attached (abutted) suffix multiplier(s),   the suffix(es) could be:   an alphabetic (named) multiplier which could be abbreviated    metric  multiplier(s) which can be specified multiple times   "binary" multiplier(s) which can be specified multiple times   explanation marks (!) which indicate a factorial or multifactorial The (decimal) numbers can be expressed generally as: {±} {digits} {.} {digits} ────── or ────── {±} {digits} {.} {digits} {E or e} {±} {digits} where:   numbers won't have embedded blanks   (contrary to the expaciated examples above where whitespace was used for readability)   this task will only be dealing with decimal numbers,   both in the   mantissa   and   exponent   ±   indicates an optional plus or minus sign   (+   or   -)   digits are the decimal digits   (0 ──► 9)   the digits can have comma(s) interjected to separate the   periods   (thousands)   such as:   12,467,000   .   is the decimal point, sometimes also called a   dot   e   or   E   denotes the use of decimal exponentiation   (a number multiplied by raising ten to some power) This isn't a pure or perfect definition of the way we express decimal numbers,   but it should convey the intent for this task. The use of the word   periods   (thousands) is not meant to confuse, that word (as used above) is what the comma separates; the groups of decimal digits are called periods,   and in almost all cases, are groups of three decimal digits. If an   e   or   E   is specified, there must be a legal number expressed before it,   and there must be a legal (exponent) expressed after it. Also, there must be some digits expressed in all cases,   not just a sign and/or decimal point. Superfluous signs, decimal points, exponent numbers, and zeros   need not be preserved. I.E.:       +7   007   7.00   7E-0   7E000   70e-1     could all be expressed as 7 All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity. Abbreviated alphabetic suffixes to be supported   (where the capital letters signify the minimum abbreation that can be used) PAIRs multiply the number by 2 (as in pairs of shoes or pants) SCOres multiply the number by 20 (as 3score would be 60) DOZens multiply the number by 12 GRoss multiply the number by 144 (twelve dozen) GREATGRoss multiply the number by 1,728 (a dozen gross) GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power) Note that the plurals are supported, even though they're usually used when expressing exact numbers   (She has 2 dozen eggs, and dozens of quavas) Metric suffixes to be supported   (whether or not they're officially sanctioned) K multiply the number by 10^3 kilo (1,000) M multiply the number by 10^6 mega (1,000,000) G multiply the number by 10^9 giga (1,000,000,000) T multiply the number by 10^12 tera (1,000,000,000,000) P multiply the number by 10^15 peta (1,000,000,000,000,000) E multiply the number by 10^18 exa (1,000,000,000,000,000,000) Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000) Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000) X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000) W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000) V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000) U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) Binary suffixes to be supported   (whether or not they're officially sanctioned) Ki multiply the number by 2^10 kibi (1,024) Mi multiply the number by 2^20 mebi (1,048,576) Gi multiply the number by 2^30 gibi (1,073,741,824) Ti multiply the number by 2^40 tebi (1,099,571,627,776) Pi multiply the number by 2^50 pebi (1,125,899,906,884,629) Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976) Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424) Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176) Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224) Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376) Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024) Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) All of the metric and binary suffixes can be expressed in   lowercase,   uppercase,   or   mixed case. All of the metric and binary suffixes can be   stacked   (expressed multiple times),   and also be intermixed: I.E.:       123k   123K   123GKi   12.3GiGG   12.3e-7T   .78E100e Factorial suffixes to be supported ! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120 !! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384 !!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80 !!!! compute the quadruple factorial product: 8! is 8 × 4 = 32 !!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24 ··· the number of factorial symbols that can be specified is to be unlimited   (as per what can be entered/typed) ··· Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein. Multifactorials aren't to be confused with   super─factorials     where   (4!)!   would be   (24)!. Task   Using the test cases (below),   show the "expanded" numbers here, on this page.   For each list, show the input on one line,   and also show the output on one line.   When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.   For each result (list) displayed on one line, separate each number with two blanks.   Add commas to the output numbers were appropriate. Test cases 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre 1,567 +1.567k 0.1567e-2m 25.123kK 25.123m 2.5123e-00002G 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei -.25123e-34Vikki 2e-77gooGols 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!! where the last number for the factorials has nine factorial symbols   (!)   after the   9 Related tasks   Multifactorial                 (which has a clearer and more succinct definition of multifactorials.)   Factorial 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
#zkl
zkl
var [const] BI=Import.lib("zklBigNum"); // GMP var kRE,kD, aRE,aD;   kRE,kD = ki(); aRE,aD = abrevCreate();   fcn naSuffixes(numStr){ var [const] numRE=RegExp(0'^([+-]*\.*\d+[.]*\d*E*[+-]*\d*)^), bangRE=RegExp(0'^(!+)^);   nstr:=(numStr - " ,").toUpper(); numRE.search(nstr); nstr,r := nstr[numRE.matched[0][1],*], numRE.matched[1]; if(r.matches("*[.E]*")) r=r.toFloat(); // arg! if(r.matches("*[.E]*")) r=r.toFloat(); // arg! else r=BI(r);   reg z; do{ z=nstr; // use this to see if we actually did anything if(aRE.search(nstr)){ ns,k := aRE.matched; // ((0,3),"SCO") re,b := aD[k]; // (RegExp("R|RE|RES"),BI(20)), nstr = nstr[ns[1],*]; if(re.search(nstr)) nstr=nstr[re.matched[0][1],*]; # remove abbrev tail r=r*b; continue; }else if(kRE.search(nstr)){ r*=kD[kRE.matched[1]]; // "K":1000 ... nstr=nstr[kRE.matched[0][1],*]; continue; }else if(bangRE.search(nstr)){ // floats are converted to int n,k,z := r.toInt(), bangRE.matched[0][1], n - k; r,nstr = BI(n), nstr[k,*]; while(z>0){ r.mul(z); z-=k; } continue; } }while(nstr and z!=nstr); r }   fcn ki{ // case insensitive: k, ki, ss:="K M G T P E Z Y X W V U".split(); d:=Dictionary(); ss.zipWith(d.add,[3..3*(ss.len()),3].apply(BI(10).pow)); # E:1e+18 ss.apply("append","I") .zipWith(d.add,[10..10*(ss.len()),10].apply(BI(2).pow)); # EI:1.15292e+18 re:="([%s]I\\?)".fmt(ss.concat()); // "([KMGTPEZYXWVU]I\?)" return(RegExp(re),d); } fcn abrevCreate{ var upDown=RegExp("([A-Z]+)(.*)"); s:="PAIRs 2; SCOres 20; DOZens 12; GREATGRoss 1728; GRoss 144; GOOGOLs 10e100".split(";"); abrevs,re := Dictionary(), Sink(String); foreach an in (s){ a,n := an.split(); upDown.search(a); u,d := upDown.matched[1,2]; d=d.len().pump(List, // "R|RE|RES" '+(1),d.get.fp(0),"toUpper").reverse().concat("|"); abrevs.add(u,T(RegExp(d),BI(n))); re.write(u," "); } // "PAIR|SCO|DOZ|GR|GREATGR|GOOGOL" re=RegExp("(%s)".fmt(re.close().strip().replace(" ","|"))); return(re,abrevs); }
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
#Haskell
Haskell
module Main where   import Text.Printf (printf) import System.Environment (getArgs, getProgName)   tochka = ("tochka" , 0.000254) liniya = ("liniya" , 0.00254) centimeter = ("centimeter", 0.01) diuym = ("diuym" , 0.0254) vershok = ("vershok" , 0.04445) piad = ("piad" , 0.1778) fut = ("fut" , 0.3048) arshin = ("arshin" , 0.7112) meter = ("meter" , 1.0) sazhen = ("sazhen" , 2.1336) kilometer = ("kilometer" , 1000.0) versta = ("versta" , 1066.8) milia = ("milia" , 7467.6)   units :: [(String, Double)] units = [tochka, liniya, centimeter, diuym, vershok, piad, fut, arshin, meter, sazhen, kilometer, versta, milia]     convert :: Double -> Double -> IO () convert num factor = mapM_ (\(unit, fac) -> printf "| %-10s | %-22f|\n" unit (num * factor / fac)) units   main :: IO () main = do args <- getArgs case args of [x,y] | [(num, "")] <- reads x :: [(Double, String)] , (Just factor) <- lookup y units -> convert num factor (_) -> do name <- getProgName printf "Arguments were wrong - please use ./%s <number> <unit>\n" name
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.
#JavaScript
JavaScript
<html style="margin: 0;"> <head> <title>Minimal WebGL Example</title> <!-- This use of <script> elements is so that we can have multiline text without quoting it inside of JavaScript; the web browser doesn't actually do anything besides store the text of these. --> <script id="shader-fs" type="x-shader/x-fragment"> precision highp float; varying vec4 v_color; void main(void) { // "Varying" variables are implicitly interpolated across triangles. gl_FragColor = v_color; } </script> <script id="shader-vs" type="x-shader/x-vertex"> attribute vec3 a_position; attribute vec4 a_color; varying vec4 v_color; void main(void) { gl_Position = vec4(a_position, 1.0); v_color = a_color; } </script> <script type="text/javascript"> function getShader(gl, id) { var scriptElement = document.getElementById(id); // Create shader object var shader; if (scriptElement.type == "x-shader/x-fragment") shader = gl.createShader(gl.FRAGMENT_SHADER); else if (scriptElement.type == "x-shader/x-vertex") shader = gl.createShader(gl.VERTEX_SHADER); else throw new Error("unknown shader script type"); // Compile shader from source gl.shaderSource(shader, scriptElement.textContent); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader)); return shader; } </script> </head> <body style="margin: 0;"> <canvas id="glcanvas" style="border: none; margin: auto; display: block;" width="640" height="480"></canvas> <script type="text/javascript"> var canvas = document.getElementById("glcanvas");   // Get WebGL context. var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) throw new Error("WebGL context not found");   // Create shader program from vertex and fragment shader code. var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, getShader(gl, "shader-vs")); gl.attachShader(shaderProgram, getShader(gl, "shader-fs")); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(shaderProgram));   // Specify to render using that program. gl.useProgram(shaderProgram);   // Get the indexes to communicate vertex attributes to the program. var positionAttr = gl.getAttribLocation(shaderProgram, "a_position"); var colorAttr = gl.getAttribLocation(shaderProgram, "a_color"); // And specify that we will be actually delivering data to those attributes. gl.enableVertexAttribArray(positionAttr); gl.enableVertexAttribArray(colorAttr);   // Store vertex positions and colors in array buffer objects. var vertices; var positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices = [ -0.5, -0.5, 0, +0.5, -0.5, 0, -0.5, +0.5, 0 ]), gl.STATIC_DRAW); var colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1 ]), gl.STATIC_DRAW); var numVertices = vertices.length / 3; // 3 coordinates per vertex   // Set GL state gl.clearColor(0.3, 0.3, 0.3, 1.0); gl.enable(gl.DEPTH_TEST); gl.viewport(0, 0, gl.drawingBufferWidth || canvas.width, gl.drawingBufferHeight || canvas.height);   // Draw scene. // If this were an animation, everything after this point would go in a main loop. // Clear frame. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Specify the array data to render. // 3 and 4 are the lengths of the vectors (3 for XYZ, 4 for RGBA). gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.vertexAttribPointer(positionAttr, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer); gl.vertexAttribPointer(colorAttr, 4, gl.FLOAT, false, 0, 0); // Draw triangles using the specified arrays. gl.drawArrays(gl.TRIANGLES, 0, numVertices);   // Check for errors. var e; while (e = gl.getError()) console.log("GL error", e); </script> </body> </html>
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
#ERRE
ERRE
  PROGRAM ONE_OF_N   DIM CNT[10]   PROCEDURE ONE_OF_N(N->L) LOCAL I FOR I=1 TO N DO IF RND(1)<=1.0/I THEN L=I END IF END FOR END PROCEDURE   BEGIN N=10 RANDOMIZE(TIMER)  ! init FOR TEST=1 TO 1000000 DO ONE_OF_N(N->L) CNT[L]+=1 END FOR FOR I=1 TO N DO PRINT(CNT[I];) END FOR PRINT END PROGRAM  
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
#Euphoria
Euphoria
-- One of n lines in a file include std/rand.e include std/math.e   function one_of_n(integer n) integer line_num = 1 for i = 2 to n do if rnd() < 1 / i then line_num = i end if end for return line_num end function   procedure main() integer num_reps = 1000000, num_lines_in_file = 10 sequence lines = repeat(0,num_lines_in_file) for i = 1 to num_reps do lines[one_of_n(num_lines_in_file)] += 1 end for for i = 1 to num_lines_in_file do printf(1,"Number of times line %d was selected: %g\n", {i,lines[i]}) end for printf(1,"Total number selected: %d\n", sum(lines) ) end procedure   main()  
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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 Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Scala
Scala
def order[T](input: Seq[T], using: Seq[T], used: Seq[T] = Seq()): Seq[T] = if (input.isEmpty || used.size >= using.size) input else if (using diff used contains input.head) using(used.size) +: order(input.tail, using, used :+ input.head) else input.head +: order(input.tail, using, used)
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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 Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Sidef
Sidef
func dsort(m, n) { var h = Hash() n.each {|item| h{item} := 0 ++ } m.map {|item| h{item} := 0 -- > 0 ? n.shift : item} }   <<'EOT'.lines.each { |line| the cat sat on the mat | mat cat the cat sat on the mat | cat mat A B C A B C A B C | C A C A A B C A B D A B E | E A D A A B | B A B | B A A B B A | B A EOT var (a, b) = line.split('|').map{.words}... say "#{a.to_s} | #{b.to_s} -> #{dsort(a.clone, b.clone).to_s}" }
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
#Lua
Lua
  function showTable(tbl) if type(tbl)=='table' then local result = {} for _, val in pairs(tbl) do table.insert(result, showTable(val)) end return '{' .. table.concat(result, ', ') .. '}' else return (tostring(tbl)) end end   function sortTable(op) local tbl = op.table or {} local column = op.column or 1 local reverse = op.reverse or false local cmp = op.cmp or (function (a, b) return a < b end) local compareTables = function (a, b) local result = cmp(a[column], b[column]) if reverse then return not result else return result end end table.sort(tbl, compareTables) end   A = {{"quail", "deer", "snake"}, {"dalmation", "bear", "fox"}, {"ant", "cougar", "coyote"}} print('original', showTable(A))   sortTable{table=A} print('defaults', showTable(A))   sortTable{table=A, column=2} print('col 2 ', showTable(A))   sortTable{table=A, column=3} print('col 3 ', showTable(A))   sortTable{table=A, column=3, reverse=true} print('col 3 rev', showTable(A))   sortTable{table=A, cmp=(function (a, b) return #a < #b end)} print('by length', showTable(A))  
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() write( if list_llt([1,2,1,3,2],[1,2,0,4,4,0,0,0]) then "true" else "false" ) end     procedure list_llt(L1,L2) #: returns L2 if L1 lexically lt L2 or fails every i := 1 to min(*L1,*L2) do if L1[i] << L2[i] then return L2 else if L1[i] >> L2[i] then fail if *L1 < *L2 then return L2 end
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#zkl
zkl
fcn pascalTriangle(n){ // n<=0-->"" foreach i in (n){ c := 1; print(" "*(2*(n-1-i))); foreach k in (i+1){ print("%3d ".fmt(c)); c = c * (i-k)/(k+1); } println(); } }   pascalTriangle(8);
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Scilab
Scilab
$ syntax expr: .(). + .() is -> 7;
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Seed7
Seed7
$ syntax expr: .(). + .() is -> 7;
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Sidef
Sidef
1+2 * 3+4 # means: (1+2) * (3+4)
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Simula
Simula
5 + b negated. "same as 5 + (b negated); unary > binary" a abs - b sqrt "same as (a abs) - (b sqrt); unary > binary" a bitAnd:1+a abs. "same as a bitAnd:(1+(a abs)); unary > binary > keyword" (a bitAnd:1+a) bitOr:(b bitAnd:1+2 abs). "ditto"   "Beginners might be confused by:" 5 + a * b "same as (5 + a) * b; all binary; therefore left to right"
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
#Huginn
Huginn
import Algorithms as algo; import Mathematics as math; import Network as net; import Text as text;   main( argv_ ) { url = size( argv_ ) > 1  ? argv_[1]  : "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"; words = algo.materialize( algo.map( net.get( url ).stream, string.strip ), list ); ordered = algo.materialize( algo.filter( words, @( word ){ word == ∑( algo.map( algo.sorted( word ), string ) ); } ), list ); maxLen = algo.reduce( ordered, @( x, y ){ math.max( x, size( y ) ); }, 0 ); maxOrderedWords = algo.materialize( algo.filter( ordered, @[maxLen]( word ){ size( word ) == maxLen; } ), list ); print( "{}\n".format( text.join( algo.sorted( maxOrderedWords ), " " ) ) ); return ( 0 ); }
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
#Icon_and_Unicon
Icon and Unicon
link strings   procedure main(A) f := open(\A[1]) | stop("Give dictionary file name on command line") every (maxLen := 0, maxLen <= *(w := !f), w == csort(w)) do { if maxLen <:= *w then maxList := [] #discard any shorter sorted words put(maxList, w) } every write(!\maxList) end
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
#PicoLisp
PicoLisp
(de palindrome? (S) (= (setq S (chop S)) (reverse S)) )
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
#Common_Lisp
Common Lisp
(defstruct uncertain-number (value 0 :type number) (uncertainty 0 :type number))   (defmethod print-object ((n uncertain-number) stream) (format stream "~,2F ± ~,2F" (uncertain-number-value n) (uncertain-number-uncertainty n)))   (defun ~+ (n1 n2) (let* ((value1 (uncertain-number-value n1)) (value2 (uncertain-number-value n2)) (uncertainty1 (uncertain-number-uncertainty n1)) (uncertainty2 (uncertain-number-uncertainty n2)) (value (+ value1 value2)) (uncertainty (sqrt (+ (* uncertainty1 uncertainty1) (* uncertainty2 uncertainty2))))) (make-uncertain-number :value value :uncertainty uncertainty)))   (defun negate (n) (make-uncertain-number :value (- (uncertain-number-value n)) :uncertainty (uncertain-number-uncertainty n)))   (defun ~- (n1 n2) (~+ n1 (negate n2)))   (defun ~* (n1 n2) (let* ((value1 (uncertain-number-value n1)) (value2 (uncertain-number-value n2)) (uncertainty-ratio-1 (/ (uncertain-number-uncertainty n1) value1)) (uncertainty-ratio-2 (/ (uncertain-number-uncertainty n2) value2)) (value (* value1 value2)) (uncertainty (sqrt (* value value (+ (* uncertainty-ratio-1 uncertainty-ratio-1) (* uncertainty-ratio-2 uncertainty-ratio-2)))))) (make-uncertain-number :value value :uncertainty uncertainty)))   (defun inverse (n) (make-uncertain-number :value (/ (uncertain-number-value n)) :uncertainty (uncertain-number-uncertainty n)))   (defun ~/ (n1 n2) (~* n1 (inverse n2)))   (defun ~expt (base exp) (let* ((base-value (uncertain-number-value base)) (uncertainty-ratio (/ (uncertain-number-uncertainty base) base-value)) (value (expt base-value exp)) (uncertainty (abs (* value exp uncertainty-ratio)))) (make-uncertain-number :value value :uncertainty uncertainty)))   (defun solve () (let* ((x1 (make-uncertain-number :value 100 :uncertainty 1.1)) (y1 (make-uncertain-number :value 50 :uncertainty 1.2)) (x2 (make-uncertain-number :value 200 :uncertainty 2.2)) (y2 (make-uncertain-number :value 100 :uncertainty 2.3)) (d (~expt (~+ (~expt (~- x1 x2) 2) (~expt (~- y1 y2) 2)) 1/2))) (format t "d = ~A~%" d)))
http://rosettacode.org/wiki/Numbers_which_are_not_the_sum_of_distinct_squares
Numbers which are not the sum of distinct squares
Integer squares are the set of integers multiplied by themselves: 1 x 1 = 1, 2 × 2 = 4, 3 × 3 = 9, etc. ( 1, 4, 9, 16 ... ) Most positive integers can be generated as the sum of 1 or more distinct integer squares. 1 == 1 5 == 4 + 1 25 == 16 + 9 77 == 36 + 25 + 16 103 == 49 + 25 + 16 + 9 + 4 Many can be generated in multiple ways: 90 == 36 + 25 + 16 + 9 + 4 == 64 + 16 + 9 + 1 == 49 + 25 + 16 == 64 + 25 + 1 == 81 + 9 130 == 64 + 36 + 16 + 9 + 4 + 1 == 49 + 36 + 25 + 16 + 4 == 100 + 16 + 9 + 4 + 1 == 81 + 36 + 9 + 4 == 64 + 49 + 16 + 1 == 100 + 25 + 4 + 1 == 81 + 49 == 121 + 9 The number of positive integers that cannot be generated by any combination of distinct squares is in fact finite: 2, 3, 6, 7, etc. Task Find and show here, on this page, every positive integer than cannot be generated as the sum of distinct squares. Do not use magic numbers or pre-determined limits. Justify your answer mathematically. See also OEIS: A001422 Numbers which are not the sum of distinct squares
#Wren
Wren
var squares = (1..18).map { |i| i * i }.toList var combs = [] var results = []   // generate combinations of the numbers 0 to n-1 taken m at a time var combGen = Fn.new { |n, m| var s = List.filled(m, 0) var last = m - 1 var rc // recursive closure rc = Fn.new { |i, next| var j = next while (j < n) { s[i] = j if (i == last) { combs.add(s.toList) } else { rc.call(i+1, j+1) } j = j + 1 } } rc.call(0, 0) }   for (n in 1..324) { var all = true for (m in 1..18) { combGen.call(18, m) for (comb in combs) { var tot = (0...m).reduce(0) { |acc, i| acc + squares[comb[i]] } if (tot == n) { all = false break } } if (!all) break combs.clear() } if (all) results.add(n) }   System.print("Numbers which are not the sum of distinct squares:") System.print(results)
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.
#D
D
bool doChar(in bool odd, in void delegate() nothrow f=null) nothrow { import core.stdc.stdio, std.ascii;   immutable int c = getchar; if (!odd) c.putchar; if (c.isAlpha) return doChar(odd, { c.putchar; if (f) f(); }); if (odd) { if (f) f(); c.putchar; } return c != '.'; }   void main() { bool i = true; while (doChar(i = !i)) {} }
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.
#Delphi
Delphi
  program Odd_word_problem;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Console, System.Character;   function doChar(isOdd: boolean; f: TProc = nil): Boolean; begin var c: char := Console.ReadKey(True).KeyChar;   if not isOdd then Write(c);   if c.IsLetter then exit(doChar(isOdd, procedure begin Write(c); if assigned(f) then f(); end));   if isOdd then begin if Assigned(f) then f(); write(c); end;   exit(c <> '.');   end;   begin var i: boolean := false; while doChar(i) do i := not i; readln; end.
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
#8080_Assembly
8080 Assembly
rawio: equ 6 org 100h ;;; Initialize RNG from keypresses lxi d,keys call puts mvi b,4 ; 4*4 = 16 bytes rndini: mvi c,4 lxi h,rnddat rndin2: push b push h rndkey: call keyin ; Get key ana a jz rndkey pop h pop b xra m ; XOR into random data mov m,a inx h dcr c jnz rndin2 dcr b jnz rndini lxi d,done call puts ;;; Create and shuffle array of numbers mvi a,'1' ; Start at 1 mvi b,9 ; 9 items lxi h,list mklst: mov m,a ; Store item inr a ; Increment item inx h ; Increment pointer dcr b ; One fewer list jnz mklst mov m,b ; Zero-terminate the list lxi d,list+8 shuf: call rande ; Shuffle the list. E = high, L = low mov l,a ldax d ; Load current number mov b,m ; Load number to swap with mov m,a ; Store first number mov a,b ; Store second number stax d dcr e ; Move pointer back jnz shuf ; Keep going until list is shuffled lxi h,0 ; Keep score on stack push h ;;; Game loop game: lxi d,list ; Print current state call puts lxi d,list ldax d check: mov b,a ; Check if list is sorted (done) inx d ldax d ana a ; Reached end of list? jz win ; Then the list is in order cmp b ; Larger than previous? jnc check ; Then keep going lxi d,prompt call puts ; Ask for a number call getnum mov b,a ; B = high number dcr b mvi c,0 ; C = low number mvi h,listhi swap: mov l,c ; Load high number in D mov d,m mov l,b ; Load high number in E mov e,m mov m,d ; Store low number in high place mov l,c mov m,e ; Store high number in low place dcr b ; Decrement high index inr c ; Increment low index mov a,c ; Low < high? cmp b jc swap ; Then keep swapping lxi d,nl ; Print newline call puts pop h ; Increment score inx h push h jmp game win: lxi d,winmsg call puts ; Print win message lxi h,score xthl ; Retrieve score and push score output buffer lxi b,-10 ; Divisor digit: lxi d,-1 ; Quotient dgdiv: inx d ; Find digit dad b jc dgdiv mvi a,'0'+10 add l ; Store digit pop h ; Get pointer dcx h ; Decrement pointer mov m,a ; Write digit to memory push h ; Store pointer xchg ; Continue with quotient mov a,h ; Done yet? ora l jnz digit ; If not keep going pop d ; Retrieve pointer ;;; Print 0-terminated string puts: ldax d ; Get character ana a ; Is it zero? rz ; Then stop inx d ; Otherwise, increment buffer pointer push d ; Save buffer pointer mov e,a ; Print character call io pop d ; Restore buffer pointer jmp puts ; Next character ;;; Read 1-9 key gnerr: mvi e,7 call io getnum: call keyin ana a jz getnum ; If no key, wait for one cpi '1' jc gnerr ; Not valid - beep and try again cpi '9'+1 jnc gnerr push psw ; Valid - echo mov e,a call io pop psw sui '0' ret keyin: mvi e,0FFh ; Read key io: mvi c,rawio ; CP/M raw I/O call jmp 5 ;;; Random number up to E rande: call rand ani 15 cmp e jnc rande ret ;;; RNG rand: push h! lxi h,rnddat! inr m! mov a,m! inx h! xra m! inx h! xra m mov m,a! inx h! add m! mov m,a! rar! dcx h! xra m! dcx h! add m mov m,a! pop h ret prompt: db 9,' - Reverse how many? ',0 keys: db 'Please press some keys to seed the RNG...',0 done: db 'done.' nl: db 13,10,0 winmsg: db 13,10,'You win! Score = ',0 db '*****' score: db 13,10,0 listhi: equ $/256+1 list: equ listhi*256 rnddat: equ list+16  
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.
#AWK
AWK
#!/usr/bin/awk -f BEGIN { edge = 1 ruleNum = 104 # 01101000 maxGen = 9 mark = "@" space = "." initialState = ".@@@.@@.@.@.@.@..@.." width = length(initialState) delete rules delete state   initRules(ruleNum) initState(initialState, mark) for (g = 0; g < maxGen; g++) { showState(g, mark, space) nextState() } showState(g, mark, space) }   function nextState( newState, i, n) { delete newState for (i = 1; i < width - 1; i++) { n = getRuleNum(i) newState[i] = rules[n] } for (i = 0; i < width; i++) { # copy, can't assign arrays state[i] = newState[i] } }   # Convert a three cell neighborhood from binary to decimal function getRuleNum(i, rn, j, p) { rn = 0 for (j = -1; j < 2; j++) { p = i + j rn = rn * 2 + (p < 0 || p > width ? edge : state[p]) } return rn }   function showState(gen, mark, space, i) { printf("%3d: ", gen) for (i = 1; i <= width; i++) { printf(" %s", (state[i] ? mark : space)) } print "" }   # Make state transition lookup table from rule number. function initRules(ruleNum, i, r) { delete rules; r = ruleNum for (i = 0; i < 8; i++) { rules[i] = r % 2 r = int(r / 2) } }   function initState(init, mark, i) { delete state srand() for (i = 0; i < width; i++) { state[i] = (substr(init, i, 1) == mark ? 1 : 0) # Given an initial string. # state[int(width/2)] = '@' # middle cell # state[i] = int(rand() * 100) < 30 ? 1 : 0 # 30% of 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.
#ALGOL_68
ALGOL 68
MODE F = PROC(LONG REAL)LONG REAL;   ############### ## left rect ## ###############   PROC left rect = (F f, LONG REAL a, b, INT n) LONG REAL: BEGIN LONG REAL h= (b - a) / n; LONG REAL sum:= 0; LONG REAL x:= a; WHILE x <= b - h DO sum := sum + (h * f(x)); x +:= h OD; sum END # left rect #;   ################# ## right rect ## #################   PROC right rect = (F f, LONG REAL a, b, INT n) LONG REAL: BEGIN LONG REAL h= (b - a) / n; LONG REAL sum:= 0; LONG REAL x:= a + h; WHILE x <= b DO sum := sum + (h * f(x)); x +:= h OD; sum END # right rect #;   ############### ## mid rect ## ###############   PROC mid rect = (F f, LONG REAL a, b, INT n) LONG REAL: BEGIN LONG REAL h= (b - a) / n; LONG REAL sum:= 0; LONG REAL x:= a; WHILE x <= b - h DO sum := sum + h * f(x + h / 2); x +:= h OD; sum END # mid rect #;   ############### ## trapezium ## ###############   PROC trapezium = (F f, LONG REAL a, b, INT n) LONG REAL: BEGIN LONG REAL h= (b - a) / n; LONG REAL sum:= f(a) + f(b); LONG REAL x:= 1; WHILE x <= n - 1 DO sum := sum + 2 * f(a + x * h ); x +:= 1 OD; (b - a) / (2 * n) * sum END # trapezium #;   ############# ## simpson ## #############   PROC simpson = (F f, LONG REAL a, b, INT n) LONG REAL: BEGIN LONG REAL h= (b - a) / n; LONG REAL sum1:= 0; LONG REAL sum2:= 0; INT limit:= n - 1; FOR i FROM 0 TO limit DO sum1 := sum1 + f(a + h * LONG REAL(i) + h / 2) OD; FOR i FROM 1 TO limit DO sum2 +:= f(a + h * LONG REAL(i)) OD; h / 6 * (f(a) + f(b) + 4 * sum1 + 2 * sum2) END # simpson #;   # test the above procedures # PROC test integrators = ( STRING legend , F function , LONG REAL lower limit , LONG REAL upper limit , INT iterations ) VOID: BEGIN print( ( legend , fixed( left rect( function, lower limit, upper limit, iterations ), -20, 6 ) , fixed( right rect( function, lower limit, upper limit, iterations ), -20, 6 ) , fixed( mid rect( function, lower limit, upper limit, iterations ), -20, 6 ) , fixed( trapezium( function, lower limit, upper limit, iterations ), -20, 6 ) , fixed( simpson( function, lower limit, upper limit, iterations ), -20, 6 ) , newline ) ) END; # test integrators # print( ( " " , " left rect" , " right rect" , " mid rect" , " trapezium" , " simpson" , newline ) ); test integrators( "x^3", ( LONG REAL x )LONG REAL: x * x * x, 0, 1, 100 ); test integrators( "1/x", ( LONG REAL x )LONG REAL: 1 / x, 1, 100, 1 000 ); test integrators( "x ", ( LONG REAL x )LONG REAL: x, 0, 5 000, 5 000 000 ); test integrators( "x ", ( LONG REAL x )LONG REAL: x, 0, 6 000, 6 000 000 );   SKIP
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
#APL
APL
risefall←{ ⍝ Determine if a number is in the sequence inSeq←0=(+/2(<->)/10(⊥⍣¯1)⊢)   ⍝ First 200 numbers ⎕←'The first 200 numbers are:' ⎕←(⊢(/⍨)inSeq¨)⍳404   ⍝ 10,000,000th number ⍝ You can't just make a list that big and filter ⍝ it, because that will just get you a WS FULL. ⍝ Instead it's necessary to loop over them the old- ⍝ fashioned way ⍞←'The 10,000,000th number is: ' ⎕←1e7{⍺=0:⍵-1 ⋄ (⍺-inSeq ⍵)∇ ⍵+1}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
#AutoHotkey
AutoHotkey
limit1 := 200, limit2 := 10000000 count := 0, result1 := result1 := "" loop{ num := A_Index if !Rise_Fall(num) continue count++ if (count <= limit1) result1 .= num . (Mod(count, 20) ? "`t" : "`n") if (count = limit2){ result2 := num break } if !mod(count, 10000) ToolTip % count } ToolTip MsgBox % "The first " limit1 " numbers in the sequence:`n" result1 "`nThe " limit2 " number in the sequence is: " result2 return   Rise_Fall(num){ rise := fall := 0 for i, n in StrSplit(num){ if (i=1) prev := n else if (n > prev) rise++ else if (n < prev) fall++ if (rise > (StrLen(num)-1) /2) || (fall > (StrLen(num)-1) /2) return 0 prev := n } if (fall = rise) return 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}
#D
D
import std.stdio, std.math;   immutable struct GaussLegendreQuadrature(size_t N, FP=double, size_t NBITS=50) { immutable static double[N] lroots, weight; alias FP[N + 1][N + 1] CoefMat;   pure nothrow @safe @nogc static this() { static FP legendreEval(in ref FP[N + 1][N + 1] lcoef, in int n, in FP x) pure nothrow { FP s = lcoef[n][n]; foreach_reverse (immutable i; 1 .. n+1) s = s * x + lcoef[n][i - 1]; return s; }   static FP legendreDiff(in ref CoefMat lcoef, in int n, in FP x) pure nothrow @safe @nogc { return n * (x * legendreEval(lcoef, n, x) - legendreEval(lcoef, n - 1, x)) / (x ^^ 2 - 1); }   CoefMat lcoef = 0.0; legendreCoefInit(/*ref*/ lcoef);   // Legendre roots: foreach (immutable i; 1 .. N + 1) { FP x = cos(PI * (i - 0.25) / (N + 0.5)); FP x1; do { x1 = x; x -= legendreEval(lcoef, N, x) / legendreDiff(lcoef, N, x); } while (feqrel(x, x1) < NBITS); lroots[i - 1] = x; x1 = legendreDiff(lcoef, N, x); weight[i - 1] = 2 / ((1 - x ^^ 2) * (x1 ^^ 2)); } }   static private void legendreCoefInit(ref CoefMat lcoef) pure nothrow @safe @nogc { lcoef[0][0] = lcoef[1][1] = 1; foreach (immutable int n; 2 .. N + 1) { // n must be signed. lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n; foreach (immutable i; 1 .. n + 1) lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1] - (n - 1) * lcoef[n - 2][i]) / n; } }   static public FP integrate(in FP function(/*in*/ FP x) pure nothrow @safe @nogc f, in FP a, in FP b) pure nothrow @safe @nogc { immutable FP c1 = (b - a) / 2; immutable FP c2 = (b + a) / 2; FP sum = 0.0; foreach (immutable i; 0 .. N) sum += weight[i] * f(c1 * lroots[i] + c2); return c1 * sum; } }   void main() { GaussLegendreQuadrature!(5, real) glq; writeln("Roots: ", glq.lroots); writeln("Weight: ", glq.weight); writefln("Integrating exp(x) over [-3, 3]: %10.12f", glq.integrate(&exp, -3, 3)); writefln("Compred to actual:  %10.12f", 3.0.exp - exp(-3.0)); }
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.
#Groovy
Groovy
class Entity implements Serializable { static final serialVersionUID = 3504465751164822571L String name = 'Thingamabob' public String toString() { return name } }   class Person extends Entity implements Serializable { static final serialVersionUID = -9170445713373959735L Person() { name = 'Clement' } Person(name) { this.name = name } }
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.
#Haskell
Haskell
{-# LANGUAGE DeriveGeneric #-}   module Main (main) where   import qualified Data.ByteString.Lazy as ByteString (readFile, writeFile) import Data.Binary (Binary) import qualified Data.Binary as Binary (decode, encode) import GHC.Generics (Generic)   data Employee = Manager String String | IndividualContributor String String deriving (Generic, Show) instance Binary Employee   main :: IO () main = do ByteString.writeFile "objects.dat" $ Binary.encode [ IndividualContributor "John Doe" "Sales" , Manager "Jane Doe" "Engineering" ]   bytes <- ByteString.readFile "objects.dat" let employees = Binary.decode bytes print (employees :: [Employee])
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
#Befunge
Befunge
055*46*146*1->00p 36268>5\:4\:2v >\#%"O"/#:3#:+#< g48*- >1-:!#v_\1+::"O"%\"O"/v >-#2:#\8#1`#:|#-1:-1\7_^#`g00:+<>\#%"O"/#::$#<3#$+g48*-v^\,+*+ 55!:*!!-"|":g+3< >$ 36 26 58 49 81 36 26 10 \1-:#^\_^#:-1\+<00_@#:>#<$< DI know an old lady who swallowed a F.|I don't know why she swallowed the 8.|Pe rhaps she'll die.||5.|She swallowed the / to catch the $fly0. To swallow a 'spi derS.|That wriggled and jiggled and tickled inside her%Bird/.|Quite absurd$Cat- .|Fancy that$Dog-.|What a hog$Pig7.|Her mouth was so big%Goat=.|She just opened her throat$Cow3.|I don't know how'Donkey6.|It was rather wonky&Horse:.|She's d ead, of course!|
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
#C
C
#include <stdio.h> static char const *animals[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; static char const *verses[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine that. She swallowed a cat", "What a hog to swallow a dog", "She just opened her throat and swallowed that goat", "I don't know how she swallowed that cow", "She's dead of course" };   #define LEN(ARR) (sizeof ARR / sizeof *ARR)   int main(void) { for (size_t i = 0; i < LEN(animals); i++) { printf("There was an old lady who swallowed a %s\n%s\n", animals[i], verses[i]); for (size_t j = i; j > 0 && i < LEN(animals) - 1; j--) { printf("She swallowed the %s to catch the %s\n", animals[j], animals[j-1]); if (j == 1) { printf("%s\n", verses[0]); } } } }
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
#J
J
  NB. Use, linux. NB. $ /usr/local/j64-801/bin/jconsole j.ijs 8 meter   UNIT2MULT =: /:~ _ ".&.>@:{:@:]`1:`]}"1<;._2@:(,&':');._2 'arshin:0.7112,centimeter:0.01,diuym:0.0254,fut:0.3048,kilometer:1000.0,liniya:0.00254,meter:1.0,milia:7467.6,piad:0.1778,sazhen:2.1336,tochka:0.000254,vershok:0.04445,versta:1066.8,'   exit 3 : 0 :: 1: a: -.~ _3 {. ARGV if. 3 ~: # y do. smoutput 'ERROR. Need two arguments - number then units' else. VALUE =: _ ". _2 {:: y if. _ = | VALUE do. smoutput 'ERROR. First argument must be a (float) number' else. UNIT =: {: y UNITS =: 0&{"1 UNIT2MULT if. UNIT-.@:e.UNITS do. smoutput 'ERROR. Only know the following units: ' , deb , ,&' '&> UNITS else. smoutput deb(,,&' '&>_2{.y),'to:' smoutput UNITS ,. (VALUE * (< 1 ,~ UNITS i. UNIT) {:: UNIT2MULT) %&.> {:"1 UNIT2MULT end. end. end. )  
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
#Java
Java
public class OldRussianMeasures {   final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"};   final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6};   public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s %s to: %n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s: %g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit");   }   public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }
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.
#Julia
Julia
using Makie   mesh([(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], shading = false)  
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.
#Kotlin
Kotlin
// Kotlin Native version 0.3   import kotlinx.cinterop.* import opengl.*   fun paint() { glClearColor(0.3f, 0.3f, 0.3f, 0.0f) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)   glShadeModel(GL_SMOOTH)   glLoadIdentity() glTranslatef(-15.0f, -15.0f, 0.0f)   glBegin(GL_TRIANGLES) glColor3f(1.0f, 0.0f, 0.0f) glVertex2f(0.0f, 0.0f) glColor3f(0.0f, 1.0f, 0.0f) glVertex2f(30.0f, 0.0f) glColor3f(0.0f, 0.0f, 1.0f) glVertex2f(0.0f, 30.0f) glEnd()   glFlush() }   fun reshape(width: Int, height: Int) { 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) }   fun main(args: Array<String>) { memScoped { val argc = alloc<IntVar>().apply { value = 0 } glutInit(argc.ptr, null) }   glutInitWindowSize(640, 480) glutCreateWindow("Triangle")   glutDisplayFunc(staticCFunction(::paint)) glutReshapeFunc(staticCFunction(::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
#F.23
F#
open System   [<EntryPoint>] let main args = let rnd = new Random()   let one_of_n n = let rec loop i r = if i >= n then r else if rnd.Next(i + 1) = 0 then loop (i + 1) i else loop (i + 1) r loop 1 0   let test n trials = let ar = Array.zeroCreate n for i = 1 to trials do let d = one_of_n n ar.[d] <- 1 + ar.[d] Console.WriteLine (String.Join(" ", ar))   test 10 1000000 0
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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 Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Swift
Swift
func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] { let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 }) let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in cur.0.append(cur.2[el, default: 0] > 0 ? cur.1.removeFirst() : el) cur.2[el]? -= 1 })   return reduced.0 }   print(disjointOrder(m: ["the", "cat", "sat", "on", "the", "mat"], n: ["mat", "cat"])) print(disjointOrder(m: ["the", "cat", "sat", "on", "the", "mat"], n: ["cat", "mat"])) print(disjointOrder(m: ["A", "B", "C", "A", "B", "C", "A", "B", "C"], n: ["C", "A", "C", "A"])) print(disjointOrder(m: ["A", "B", "C", "A", "B", "D", "A", "B", "E"], n: ["E", "A", "D", "A"])) print(disjointOrder(m: ["A", "B"], n: ["B"])) print(disjointOrder(m: ["A", "B"], n: ["B", "A"])) print(disjointOrder(m: ["A", "B", "B", "A"], n: ["B", "A"]))
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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 Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Tcl
Tcl
proc orderDisjoint {theList theOrderList} { foreach item $theOrderList {incr n($item)} set is {} set i 0 foreach item $theList { if {[info exist n($item)] && [incr n($item) -1] >= 0} { lappend is $i } incr i } foreach item $theOrderList i $is {lset theList $i $item} return $theList }
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
#Maple
Maple
  OptionalSort := proc(input, { ordering :: Or(procedures,identical("lexicographic")) := "lexicographic", column :: posint := 1, reverse :: truefalse := false } ) local compare; if ordering = "lexicographic" then compare := (x,y)->evalb(`if`(reverse,x[column]>=y[column],x[column]<=y[column])); else compare := (x,y)->`if`(reverse,ordering(x[column],y),ordering(y,x)); end if; sort( input, compare ); end proc:
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False}; OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True, SortBy[x ,#[[OptionValue[column]]]&]//Reverse, SortBy[x,#[[OptionValue[column]]]&] ]   OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}} ] ->{{,q,z},{a,b,c},{zap,zip,Zot}}   OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}},{ordering->lexicographic,column->2,reverse-> True} ] ->{{zap,zip,Zot},{,q,z},{a,b,c}}
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.
#J
J
before=: -.@(-: /:~)@,&<~
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.
#Java
Java
import java.util.Arrays; import java.util.List;   public class ListOrder{ public static boolean ordered(double[] first, double[] second){ if(first.length == 0) return true; if(second.length == 0) return false; if(first[0] == second[0]) return ordered(Arrays.copyOfRange(first, 1, first.length), Arrays.copyOfRange(second, 1, second.length)); return first[0] < second[0]; }   public static <T extends Comparable<? super T>> boolean ordered(List<T> first, List<T> second){ int i = 0; for(; i < first.size() && i < second.size();i++){ int cmp = first.get(i).compareTo(second.get(i)); if(cmp == 0) continue; if(cmp < 0) return true; return false; } return i == first.size(); }   public static boolean ordered2(double[] first, double[] second){ int i = 0; for(; i < first.length && i < second.length;i++){ if(first[i] == second[i]) continue; if(first[i] < second[i]) return true; return false; } return i == first.length; } }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 INPUT "How many rows? ";n 15 IF n<1 THEN GO TO 210 20 DIM c(n) 25 DIM d(n) 30 LET c(1)=1 35 LET d(1)=1 40 FOR r=1 TO n 50 FOR i=1 TO (n-r) 60 PRINT " "; 70 NEXT i 80 FOR i=1 TO r 90 PRINT c(i);" "; 100 NEXT i 110 PRINT 120 IF r>=n THEN GO TO 140 130 LET d(r+1)=1 140 FOR i=2 TO r 150 LET d(i)=c(i-1)+c(i) 160 NEXT i 165 IF r>=n THEN GO TO 200 170 FOR i=1 TO r+1 180 LET c(i)=d(i) 190 NEXT i 200 NEXT r
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Smalltalk
Smalltalk
5 + b negated. "same as 5 + (b negated); unary > binary" a abs - b sqrt "same as (a abs) - (b sqrt); unary > binary" a bitAnd:1+a abs. "same as a bitAnd:(1+(a abs)); unary > binary > keyword" (a bitAnd:1+a) bitOr:(b bitAnd:1+2 abs). "ditto"   "Beginners might be confused by:" 5 + a * b "same as (5 + a) * b; all binary; therefore left to right"
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Standard_ML
Standard ML
-2^2=-(2^2)=-4 2^3^2=(2^3)^2=64 4/2π=(4/2)π=2π=6.283185307 -B/2A=-((B/2)*A)=-(B/2)*A
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#Tcl
Tcl
-2^2=-(2^2)=-4 2^3^2=(2^3)^2=64 4/2π=(4/2)π=2π=6.283185307 -B/2A=-((B/2)*A)=-(B/2)*A
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
#Io
Io
file := File clone openForReading("./unixdict.txt") words := file readLines file close   maxLen := 0 orderedWords := list() words foreach(word, if( (word size >= maxLen) and (word == (word asMutable sort)), if( word size > maxLen, maxLen = word size orderedWords empty ) orderedWords append(word) ) )   orderedWords join(" ") println
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
#Pike
Pike
int main(){ if(pal("rotator")){ write("palindrome!\n"); } if(!pal("asdf")){ write("asdf isn't a palindrome.\n"); } }   int pal(string input){ if( reverse(input) == input ){ return 1; } else { return 0; } }
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
#D
D
import std.stdio, std.math, std.string, std.typecons, std.traits;   const struct Imprecise { private const double value, delta;   this(in double v, in double d) pure nothrow { this.value = v; this.delta = abs(d); }   enum IsImprecise(T) = is(Unqual!T == Unqual!(typeof(this)));   I reciprocal() const pure nothrow { return I(1.0 / value, delta / (value ^^ 2)); }   string toString() const { return format("I(value=%g, delta=%g)", value, delta); }   I opUnary(string op:"-")() const pure nothrow { return I(-this.value, this.delta); }   I opBinary(string op:"+", T)(in T other) const pure nothrow if (isNumeric!T || IsImprecise!T) { static if (IsImprecise!T) return I(this.value + other.value, (this.delta ^^ 2 + other.delta ^^ 2) ^^ 0.5); else return I(this.value + other, this.delta); }   I opBinaryRight(string op:"+", T)(in T other) const pure nothrow if (isNumeric!T) { return I(this.value + other, this.delta); }   I opBinary(string op:"-", T)(in T other) const pure nothrow if (isNumeric!T || IsImprecise!T) { return this + (-other); }   I opBinaryRight(string op:"-", T)(in T other) const pure nothrow if (isNumeric!T) { return this - other; }   I opBinary(string op:"*", T)(in T other) const pure nothrow if (isNumeric!T || IsImprecise!T) { static if (IsImprecise!T) { auto f = this.value * other.value; return I(f, f * ((delta / value) ^^ 2 + (other.delta / other.value) ^^ 2) ^^ 0.5); } else return I(this.value * other, this.delta * other); }   I opBinaryRight(string op:"*", T)(in T other) const pure nothrow if (isNumeric!T) { return this * other; }   I opBinary(string op:"/", T)(in T other) const pure nothrow if (isNumeric!T || IsImprecise!T) { static if (IsImprecise!T) return this * other.reciprocal(); else return I(this.value / other, this.delta / other); }   I opBinaryRight(string op:"/", T)(in T other) const pure nothrow if (isNumeric!T) { return this / other; }   I opBinary(string op:"^^", T)(in T other) const pure nothrow if (isNumeric!T) { auto f = this.value ^^ other; return I(f, f * other * (this.delta / this.value)); } }   alias I = Imprecise;   auto distance(T1, T2)(in T1 p1, in T2 p2) pure nothrow { return ((p1[0] - p2[0]) ^^ 2 + (p1[1] - p2[1]) ^^ 2) ^^ 0.5; }   void main() { immutable x1 = I(100, 1.1); immutable x2 = I(200, 2.2); immutable y1 = I( 50, 1.2); immutable y2 = I(100, 2.3);   immutable p1 = tuple(x1, y1); immutable p2 = tuple(x2, y2); writefln("Point p1: (%s, %s)", p1[0], p1[1]); writefln("Point p2: (%s, %s)", p2[0], p2[1]); writeln("Distance(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.
#EchoLisp
EchoLisp
  (lib 'sequences) (define input-stream null) (define output-stream "")   ;;--------------------------- ;; character I/O simulation ;; -------------------------- (define (read-char) (next input-stream)) ;; #f if EOF (define (write-char c) (when c (set! output-stream (string-append output-stream c))))   (define (init-streams sentence) (set! input-stream (procrastinator sentence)) (set! output-stream ""))   ;;--------------------------------- ;; task , using read-char/write-char ;;----------------------------------   (define (flop) ; reverses, and returns first non-alpha after word, or EOF (define c (read-char)) (if (string-alphabetic? c) (begin0 (flop) (write-char c)) c))   (define (flip) (define c (read-char)) (if (string-alphabetic? c) (begin (write-char c) (flip)) c))   (define (task sentence) (init-streams sentence) (while (and (write-char (flip)) (write-char (flop)))) output-stream )      
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
#11l
11l
V data = Array(‘139275486’) V trials = 0   L data != sorted(data) trials++ V flip = Int(input(‘###2: LIST: '#.' Flip how many?: ’.format(trials, data.join(‘ ’)))) data.reverse_range(0 .< flip)   print("\nYou took #. attempts to put the digits in order!".format(trials))
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.
#11l
11l
F f([Int]? &a) I a != N a.append(1)   f(N) [Int] arr f(&arr) print(arr)
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.
#BASIC
BASIC
DECLARE FUNCTION life$ (lastGen$) DECLARE FUNCTION getNeighbors! (group$) CLS start$ = "_###_##_#_#_#_#__#__" numGens = 10 FOR i = 0 TO numGens - 1 PRINT "Generation"; i; ": "; start$ start$ = life$(start$) NEXT i   FUNCTION getNeighbors (group$) ans = 0 IF (MID$(group$, 1, 1) = "#") THEN ans = ans + 1 IF (MID$(group$, 3, 1) = "#") THEN ans = ans + 1 getNeighbors = ans END FUNCTION   FUNCTION life$ (lastGen$) newGen$ = "" FOR i = 1 TO LEN(lastGen$) neighbors = 0 IF (i = 1) THEN 'left edge IF MID$(lastGen$, 2, 1) = "#" THEN neighbors = 1 ELSE neighbors = 0 END IF ELSEIF (i = LEN(lastGen$)) THEN 'right edge IF MID$(lastGen$, LEN(lastGen$) - 1, 1) = "#" THEN neighbors = 1 ELSE neighbors = 0 END IF ELSE 'middle neighbors = getNeighbors(MID$(lastGen$, i - 1, 3)) END IF   IF (neighbors = 0) THEN 'dies or stays dead with no neighbors newGen$ = newGen$ + "_" END IF IF (neighbors = 1) THEN 'stays with one neighbor newGen$ = newGen$ + MID$(lastGen$, i, 1) END IF IF (neighbors = 2) THEN 'flips with two neighbors IF MID$(lastGen$, i, 1) = "#" THEN newGen$ = newGen$ + "_" ELSE newGen$ = newGen$ + "#" END IF END IF NEXT i life$ = newGen$ END FUNCTION
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.
#ALGOL_W
ALGOL W
begin % compare some numeric integration methods  %   long real procedure leftRect ( long real procedure f  ; long real value a, b  ; integer value n ) ; begin long real h, sum, x; h  := (b - a) / n; sum := 0; x  := a; while x <= b - h do begin sum := sum + (h * f(x)); x  := x + h end; sum end leftRect ;   long real procedure rightRect ( long real procedure f  ; long real value a, b  ; integer value n ) ; begin long real h, sum, x; h  := (b - a) / n; sum := 0; x  := a + h; while x <= b do begin sum := sum + (h * f(x)); x  := x + h end; sum end rightRect ;   long real procedure midRect ( long real procedure f  ; long real value a, b  ; integer value n ) ; begin long real h, sum, x; h  := (b - a) / n; sum := 0; x  := a; while x <= b - h do begin sum := sum + h * f(x + h / 2); x  := x + h end; sum end midRect ;   long real procedure trapezium ( long real procedure f  ; long real value a, b  ; integer value n ) ; begin long real h, sum, x; h  := (b - a) / n; sum := f(a) + f(b); x  := 1; while x <= n - 1 do begin sum := sum + 2 * f(a + x * h ); x  := x + 1 end; (b - a) / (2 * n) * sum end trapezium ;   long real procedure simpson ( long real procedure f  ; long real value a, b  ; integer value n ) ; begin long real h, sum1, sum2, x; integer limit; h  := (b - a) / n; sum1  := 0; sum2  := 0; limit := n - 1; for i := 0 until limit do sum1 := sum1 + f(a + h * i + h / 2); for i := 1 until limit do sum2 := sum2 + f(a + h * i); h / 6 * (f(a) + f(b) + 4 * sum1 + 2 * sum2) end simpson ;    % tests the above procedures  % procedure testIntegrators1 ( string(3) value legend  ; long real procedure f  ; long real value lowerLimit  ; long real value upperLimit  ; integer value iterations ) ; write( r_format := "A", r_w := 20, r_d := 6, s_w := 0, , legend , leftRect( f, lowerLimit, upperLimit, iterations ) , rightRect( f, lowerLimit, upperLimit, iterations ) , midRect( f, lowerLimit, upperLimit, iterations ) , trapezium( f, lowerLimit, upperLimit, iterations ) , simpson( f, lowerLimit, upperLimit, iterations ) ); procedure testIntegrators2 ( string(3) value legend  ; long real procedure f  ; long real value lowerLimit  ; long real value upperLimit  ; integer value iterations ) ; write( r_format := "A", r_w := 16, r_d := 2, s_w := 0, , legend , leftRect( f, lowerLimit, upperLimit, iterations ), " " , rightRect( f, lowerLimit, upperLimit, iterations ), " " , midRect( f, lowerLimit, upperLimit, iterations ), " " , trapezium( f, lowerLimit, upperLimit, iterations ), " " , simpson( f, lowerLimit, upperLimit, iterations ), " " );   begin % task test cases  % long real procedure xCubed ( long real value x ) ; x * x * x; long real procedure oneOverX ( long real value x ) ; 1 / x; long real procedure xValue ( long real value x ) ; x; write( " " , " left rect" , " right rect" , " mid rect" , " trapezium" , " simpson" ); testIntegrators1( "x^3", xCubed, 0, 1, 100 ); testIntegrators1( "1/x", oneOverX, 1, 100, 1000 ); testIntegrators2( "x ", xValue, 0, 5000, 5000000 ); testIntegrators2( "x ", xValue, 0, 6000, 6000000 ) end 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
#AWK
AWK
  # syntax: GAWK -f NUMBERS_WITH_EQUAL_RISES_AND_FALLS.AWK # converted from Go BEGIN { print("1-200:") while (1) { if (rises_equals_falls(++n)) { if (++count <= 200) { printf("%4d",n) if (count % 20 == 0) { printf("\n") } } if (count == 1E7) { printf("\n%d: %d",count,n) break } } } exit(0) } function rises_equals_falls(n, d,falls,prev,rises) { if (n < 10) { return(1) } prev = -1 while (n > 0) { d = n % 10 if (prev >= 0) { if (d < prev) { rises++ } else if (d > prev) { falls++ } } prev = d n = int(n / 10) } return(rises == falls) }  
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
#C
C
#include <stdio.h>   /* Check whether a number has an equal amount of rises * and falls */ int riseEqFall(int num) { int rdigit = num % 10; int netHeight = 0; while (num /= 10) { netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit); rdigit = num % 10; } return netHeight == 0; }   /* Get the next member of the sequence, in order, * starting at 1 */ int nextNum() { static int num = 0; do {num++;} while (!riseEqFall(num)); return num; }   int main(void) { int total, num;   /* Generate first 200 numbers */ printf("The first 200 numbers are: \n"); for (total = 0; total < 200; total++) printf("%d ", nextNum());   /* Generate 10,000,000th number */ printf("\n\nThe 10,000,000th number is: "); for (; total < 10000000; total++) num = nextNum(); printf("%d\n", num);   return 0; }
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
Numerical integration/Gauss-Legendre Quadrature
In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function W ( x ) {\displaystyle 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}
#Delphi
Delphi
program Legendre;   {$APPTYPE CONSOLE}   const Order = 5; Epsilon = 1E-12;   var Roots : array[0..Order-1] of double; Weight : array[0..Order-1] of double; LegCoef : array [0..Order,0..Order] of double;   function F(X:double) : double; begin Result := Exp(X); end;   procedure PrepCoef; var I, N : integer; begin for I:=0 to Order do for N := 0 to Order do LegCoef[I,N] := 0; LegCoef[0,0] := 1; LegCoef[1,1] := 1; For N:=2 to Order do begin LegCoef[N,0] := -(N-1) * LegCoef[N-2,0] / N; For I := 1 to Order do LegCoef[N,I] := ((2*N-1) * LegCoef[N-1,I-1] - (N-1)*LegCoef[N-2,I]) / N; end; end;   function LegEval(N:integer; X:double) : double; var I : integer; begin Result := LegCoef[n][n]; for I := N-1 downto 0 do Result := Result * X + LegCoef[N][I]; end;   function LegDiff(N:integer; X:double) : double; begin Result := N * (X * LegEval(N,X) - LegEval(N-1,X)) / (X*X-1); end;   procedure LegRoots; var I : integer; X, X1 : double; begin for I := 1 to Order do begin X := Cos(Pi * (I-0.25) / (Order+0.5)); repeat X1 := X; X := X - LegEval(Order,X) / LegDiff(Order, X); until Abs (X-X1) < Epsilon; Roots[I-1] := X; X1 := LegDiff(Order,X); Weight[I-1] := 2 / ((1-X*X) * X1*X1); end; end;   function LegInt(A,B:double) : double; var I : integer; C1, C2 : double; begin C1 := (B-A)/2; C2 := (B+A)/2; Result := 0; For I := 0 to Order-1 do Result := Result + Weight[I] * F(C1*Roots[I] + C2); Result := C1 * Result; end;   var I : integer;   begin PrepCoef; LegRoots;   Write('Roots: '); for I := 0 to Order-1 do Write (' ',Roots[I]:13:10); Writeln;   Write('Weight: '); for I := 0 to Order-1 do Write (' ', Weight[I]:13:10); writeln;   Writeln('Integrating Exp(x) over [-3, 3]: ',LegInt(-3,3):13:10); Writeln('Actual value: ',Exp(3)-Exp(-3):13:10); Readln; 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.
#J
J
lin_z_=:5!:5 serializeObject=:3 :0 p=. copath y d=. ;LF;"1(,'=:';lin__y)"0 nl__y i.4 '(',(5!:5<'p'),')(copath[cocurrent@])cocreate ''''',,d,LF )   deserializeObject=:3 :0 o=.conl 1 0!:100 y (conl 1)-.o )   coclass'room' create=:3 :'size=:y' print=:3 :'''room size '',":size'   coclass'kitchen' coinsert'room' print=:3 :'''kitchen size '',":size'   coclass'kitchenWithSink' coinsert'kitchen' print=:3 :'''kitchen with sink size '',":size'   cocurrent'base'   R=:'small' conew 'room' K=:'medium' conew 'kitchen' S=:'large' conew 'kitchenWithSink' print__R'' print__K'' print__S''     (;<@serializeObject"0 R,K,S) 1!:2 <'objects.dat'   'r1 k1 s1'=: <"0 deserializeObject 1!:1<'objects.dat' print__r1'' print__k1'' print__s1''
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.
#Java
Java
import java.io.*;   // classes must implement java.io.Serializable in order to be serializable class Entity implements Serializable { // it is recommended to hard-code serialVersionUID so changes to class // will not invalidate previously serialized objects static final long serialVersionUID = 3504465751164822571L; String name = "Entity"; public String toString() { return name; } }   class Person extends Entity implements Serializable { static final long serialVersionUID = -9170445713373959735L; Person() { name = "Cletus"; } }   public class SerializationTest { public static void main(String[] args) { Person instance1 = new Person(); System.out.println(instance1);   Entity instance2 = new Entity(); System.out.println(instance2);   // Serialize try { ObjectOutput out = new ObjectOutputStream(new FileOutputStream("objects.dat")); // open ObjectOutputStream   out.writeObject(instance1); // serialize "instance1" and "instance2" to "out" out.writeObject(instance2); out.close(); System.out.println("Serialized..."); } catch (IOException e) { System.err.println("Something screwed up while serializing"); e.printStackTrace(); System.exit(1); }   // Deserialize try { ObjectInput in = new ObjectInputStream(new FileInputStream("objects.dat")); // open ObjectInputStream   Object readObject1 = in.readObject(); // read two objects from "in" Object readObject2 = in.readObject(); // you may want to cast them to the appropriate types in.close(); System.out.println("Deserialized...");   System.out.println(readObject1); System.out.println(readObject2); } catch (IOException e) { System.err.println("Something screwed up while deserializing"); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Unknown class for deserialized object"); e.printStackTrace(); System.exit(1); } } }
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
#C.23
C#
using System;   namespace OldLady { internal class Program { private const string reason = "She swallowed the {0} to catch the {1}"; private static readonly string[] creatures = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"};   private static readonly string[] comments = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "How absurd, to swallow a bird", "Imagine that. She swallowed a cat", "What a hog to swallow a dog", "She just opened her throat and swallowed that goat", "I don't know how she swallowed that cow", "She's dead of course" };   private static void Main() { int max = creatures.Length; for (int i = 0; i < max; i++) { Console.WriteLine("There was an old lady who swallowed a {0}", creatures[i]); Console.WriteLine(comments[i]); for (int j = i; j > 0 && i < max - 1; j--) { Console.WriteLine(reason, creatures[j], creatures[j - 1]); if (j == 1) { Console.WriteLine(comments[j - 1]); } } } Console.Read(); } } }
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
#Julia
Julia
using DataStructures   const unit2mult = Dict( "arshin" => 0.7112, "centimeter" => 0.01, "diuym" => 0.0254, "fut" => 0.3048, "kilometer" => 1000.0, "liniya" => 0.00254, "meter" => 1.0, "milia" => 7467.6, "piad" => 0.1778, "sazhen" => 2.1336, "tochka" => 0.000254, "vershok" => 0.04445, "versta" => 1066.8)   @assert length(ARGS) == 2 "need two arguments - number then units"   global value try value = parse(Float64, ARGS[1]) catch error("first argument must be a (float) number") end   if isnull(value) error("first argument must be a (float) number") end unit = ARGS[2] @assert unit ∈ keys(unit2mult) "only know the following units:\n" * join(keys(unit2mult), ", ")   println("$value $unit to:") for (unt, mlt) in sort(unit2mult) @printf("  %10s: %g\n", unt, value * unit2mult[unit] / mlt) end
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
#Kotlin
Kotlin
// version 1.0.6   /* clears console on Windows 10 */ fun cls() = ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()   fun main(args: Array<String>) { val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer") val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f, 71.12f, 213.36f, 10668.0f, 74676.0f, 1.0f, 100.0f, 10000.0f) var unit: Int var value: Float var yn : String do { cls() println() for (i in 0 until units.size) println("${"%2d".format(i + 1)} ${units[i]}") println() do { print("Please choose a unit 1 to 13 : ") unit = try { readLine()!!.toInt() } catch (e: NumberFormatException) { 0 } } while (unit !in 1..13) unit-- do { print("Now enter a value in that unit : ") value = try { readLine()!!.toFloat() } catch (e: NumberFormatException) { -1.0f } } while (value < 0.0f) println("\nThe equivalent in the remaining units is:\n") for (i in 0 until units.size) { if (i == unit) continue println(" ${units[i].padEnd(10)} : ${value * convs[unit] / convs[i]}") } println() do { print("Do another one y/n : ") yn = readLine()!!.toLowerCase() } while (yn != "y" && yn != "n") } while (yn == "y") }
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.
#Liberty_BASIC
Liberty BASIC
nomainwin struct rect, x as long, y as long, x2 as long, y2 as long struct PFD, Size as word, Version as word, Flags as long,_ PixelType as char[1], ColorBits as char[1], RedBits as char[1],_ RedShift as char[1], GreenBits as char[1], GreenShift as char[1],_ BlueBits as char[1], BlueShift as char[1], AlphaBits as char[1],_ AlphaShift as char[1],AccumBits as char[1], AccumRedBits as char[1],_ AccumGreenBits as char[1], AccumBlueBits as char[1], AccumAlphaBits as char[1],_ DepthBits as char[1], StencilBits as char[1], AuxBuffers as char[1],_ LayerType as char[1], Reserved as char[1], LayerMask as long,_ VisibleMask as long, DamageMask as long PFD.Version.struct=1 PFD.ColorBits.struct=24 PFD.DepthBits.struct=16 PFD.Size.struct=len(PFD.struct) PFD.Flags.struct=37 GlColorBufferBit=16384 open "opengl32.dll" for dll as #gl open "glu32.dll" for dll as #glu WindowWidth=500 WindowHeight=500 UpperLeftX=1 UpperLeftY=1 open "Triangle" for window_nf as #main print #main,"trapclose [quit]" MainH=hwnd(#main) calldll #user32,"GetDC", MainH as ulong, MainDC as ulong calldll #gdi32,"ChoosePixelFormat", MainDC as ulong, PFD as struct, ret as long calldll #gdi32, "SetPixelFormat", MainDC as ulong, ret as long, PFD as struct, t as long calldll #gl,"wglCreateContext", MainDC as ulong, GLContext as ulong calldll #gl,"wglMakeCurrent", MainDC as ulong, GLContext as ulong, ret as long calldll #gl,"glClear", GlColorBufferBit as long, ret as long calldll #gl,"glRotated", 0 as double, 0 as double, 0 as double, 0 as double, ret as long calldll #gl,"glBegin", 4 as long, ret as long calldll #gl,"glColor3d", 0 as double, 0 as double, 255 as double, ret as long calldll #gl,"glVertex3i", -1 as long, -1 as long, 0 as long, ret as long calldll #gl,"glColor3d", 255 as double, 0 as double, 0 as double, ret as long calldll #gl,"glVertex3i", 0 as long, 1 as long, 0 as long, ret as long calldll #gl,"glColor3d", 0 as double, 255 as double, 0 as double, ret as long calldll #gl,"glVertex3i", 1 as long, -1 as long, 0 as long, ret as long calldll #gl,"glEnd", ret as void calldll #gdi32,"SwapBuffers", MainDC as ulong, ret as long wait [quit] calldll #gl,"wglMakeCurrent", 0 as ulong, 0 as ulong, ret as long calldll #gl,"wglDeleteContext", GLContext as ulong, ret as long calldll #user32, "ReleaseDC", MainH as ulong, MainDC as ulong,ret as long close #main close #glu close #gl end
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
#Factor
Factor
! rosettacode/random-line/random-line.factor USING: io kernel locals math random ; IN: rosettacode.random-line   :: random-line ( -- line ) readln :> choice! 1 :> count! [ readln dup ] [ count 1 + dup count! random zero? [ choice! ] [ drop ] if ] while drop choice ;
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
#Forth
Forth
require random.fs   : frnd rnd 0 d>f [ s" MAX-U" environment? drop 0 d>f 1/f ] fliteral f* ; : u>f 0 d>f ; : one_of_n ( u1 -- u2 ) 1 swap 1+ 2 ?do frnd i u>f 1/f f< if drop i then loop ;   create hist 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , does> swap cells + ; : simulate 1000000 0 do 1 10 one_of_n 1- hist +! loop ; : .hist cr 10 0 do i 1+ 2 .r ." : " i hist @ . cr loop ;   simulate .hist bye
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort 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 Given   M   as a list of items and another list   N   of items chosen from   M,   create   M'   as a list with the first occurrences of items from   N   sorted to be in one of the set of indices of their original occurrence in   M   but in the order given by their order in   N. That is, items in   N   are taken from   M   without replacement, then the corresponding positions in   M'   are filled by successive items from   N. For example if   M   is   'the cat sat on the mat' And   N   is   'mat cat' Then the result   M'   is   'the mat sat on the cat'. The words not in   N   are left in their original positions. If there are duplications then only the first instances in   M   up to as many as are mentioned in   N   are potentially re-ordered. For example M = 'A B C A B C A B C' N = 'C A C A' Is ordered as: M' = 'C B A C B A A B C' Show the output, here, for at least the following inputs: Data M: 'the cat sat on the mat' Order N: 'mat cat' Data M: 'the cat sat on the mat' Order N: 'cat mat' Data M: 'A B C A B C A B C' Order N: 'C A C A' Data M: 'A B C A B D A B E' Order N: 'E A D A' Data M: 'A B' Order N: 'B' Data M: 'A B' Order N: 'B A' Data M: 'A B B A' Order N: 'B A' Cf Sort disjoint sublist
#Wren
Wren
import "/fmt" for Fmt   var NULL = "\0"   var orderDisjointList = Fn.new { |m, n| var nList = n.split(" ") // first replace the first occurrence of items of 'n' in 'm' with the NULL character // which we can safely assume won't occur in 'm' naturally for (item in nList) { var ix = m.indexOf(item) if (ix >= 0) { var le = item.count m = m[0...ix] + NULL + m[ix + le..-1] } } // now successively replace the NULLs with items from nList var mList = m.split(NULL) var sb = "" for (i in 0...nList.count) sb = sb + mList[i] + nList[i] return sb + mList[-1] }   var ma = [ "the cat sat on the mat", "the cat sat on the mat", "A B C A B C A B C", "A B C A B D A B E", "A B", "A B", "A B B A" ]   var na = [ "mat cat", "cat mat", "C A C A", "E A D A", "B", "B A", "B A" ]   for (i in 0...ma.count) { Fmt.print("$-22s -> $-7s -> $s", ma[i], na[i], orderDisjointList.call(ma[i], na[i])) }
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
#Nemerle
Nemerle
Sorter (table : list[list[string]], ordering = "lexicographic", column = 0, reverse = false) : list[list[string]] { // implementation goes here }
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
#Nim
Nim
import algorithm, strutils, sugar   proc printTable(a: seq[seq[string]]) = for row in a: for x in row: stdout.write x, repeat(' ', 4 - x.len) echo "" echo ""   proc sortTable(a: seq[seq[string]], column = 0, reverse = false, ordering: (proc(a,b: string): int) = system.cmp) : seq[seq[string]] = let order = if reverse: Descending else: Ascending result = a result.sort(proc(x,y:seq[string]):int = ordering(x[column],y[column]), order)   const data = @[@["a", "b", "c"], @["", "q", "z"], @["zap", "zip", "Zot"]]   printTable data printTable sortTable(data) printTable sortTable(data, column = 2) printTable sortTable(data, column = 1) printTable sortTable(data, column = 1, reverse = true) printTable sortTable(data, ordering = (a,b) => cmp[int](b.len,a.len))
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.
#JavaScript
JavaScript
(() => { 'use strict';   // <= is already defined for lists in JS   // compare :: [a] -> [a] -> Bool const compare = (xs, ys) => xs <= ys;     // TEST return [ compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]), compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2]) ];   // --> [false, true] })()  
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#TI-83_BASIC
TI-83 BASIC
-2^2=-(2^2)=-4 2^3^2=(2^3)^2=64 4/2π=(4/2)π=2π=6.283185307 -B/2A=-((B/2)*A)=-(B/2)*A
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity   of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
#VBScript
VBScript
-2^2=(-2)^2=4 2^3^2=(2^3)^2=64
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
#J
J
require'web/gethttp' dict=: gethttp'http://www.puzzlers.org/pub/wordlists/unixdict.txt' oWords=: (#~ ] = /:~L:0) <;._2 dict-.CR  ;:inv (#~ (= >./)@:(#@>))oWords abbott accent accept access accost almost bellow billow biopsy chilly choosy choppy effort floppy glossy knotty
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have 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
#Java
Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List;   public class Ordered {   private static boolean isOrderedWord(String word){ char[] sortedWord = word.toCharArray(); Arrays.sort(sortedWord); return word.equals(new String(sortedWord)); }   public static void main(String[] args) throws IOException{ List<String> orderedWords = new LinkedList<String>(); BufferedReader in = new BufferedReader(new FileReader(args[0])); while(in.ready()){ String word = in.readLine(); if(isOrderedWord(word)) orderedWords.add(word); } in.close();   Collections.<String>sort(orderedWords, new Comparator<String>() { @Override public int compare(String o1, String o2) { return new Integer(o2.length()).compareTo(o1.length()); } });   int maxLen = orderedWords.get(0).length(); for(String word: orderedWords){ if(word.length() == maxLen){ System.out.println(word); }else{ break; } } } }
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
#PL.2FI
PL/I
is_palindrome = (text = reverse(text));
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
#F.23
F#
let sqr (x : float) = x * x let abs (x : float) = System.Math.Abs x let pow = System.Math.Pow   type Approx (value : float, sigma : float) = member this.value = value member this.sigma = sigma   static member (~-) (x : Approx) = Approx (- x.value, x.sigma) static member (%+) (x: Approx, y : float) = Approx (x.value + y, x.sigma) static member (%+) (y : float, x : Approx) = x %+ y static member (%+) (x : Approx, y : Approx) = Approx (x.value + y.value, sqrt((sqr x.sigma)+(sqr y.sigma))) static member (%-) (x: Approx, y : float) = Approx (x.value - y, x.sigma) static member (%-) (y : float, x : Approx) = (-x) %+ y static member (%-) (x : Approx, y : Approx) = x %+ (-y) static member (%*) (x : Approx, y : float) = Approx (y * x.value, abs(y * x.sigma)) static member (%*) (y : float, x : Approx) = x %* y static member (%*) (x : Approx, y : Approx) = let v = x.value * y.value Approx (v, v * sqrt(sqr(x.sigma/x.value))+sqr(y.sigma/y.value)) static member (%/) (x : Approx, y : Approx) = Approx (x.value / y.value, sqrt(sqr(x.sigma/x.value))+sqr(y.sigma/y.value)) static member (%^) (x : Approx, y : float) = if y < 0. then failwith ("Cannot raise the power with a negative number " + y.ToString()) let v = pow(x.value,y) Approx (v, abs(v * y * x.sigma / x.value))   override this.ToString() = sprintf "%.2f ±%.2f" value sigma   [<EntryPoint>] let main argv = let x1 = Approx (100., 1.1) let y1 = Approx (50., 1.2) let x2 = Approx (200., 2.2) let y2 = Approx (100., 2.3)   printfn "Distance: %A" ((((x1 %- x2) %^ 2.) %+ ((y1 %- y2) %^ 2.)) %^ 0.5) 0
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.
#Elixir
Elixir
defmodule Odd_word do def handle(s, false, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do o.(s) handle(i.(), false, i, o) end def handle(s, t, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do d = handle(i.(), :rec, i, o) o.(s) if t == true, do: handle(d, t, i, o), else: d end def handle(s, :rec, _, _), do: s def handle(?., _, _, o), do: o.(?.); :done def handle(:eof, _, _, _), do: :done def handle(s, t, i, o) do o.(s) handle(i.(), not t, i, o) end   def main do i = fn() -> IO.getn("") end o = fn(s) -> IO.write(s) end handle(i.(), false, i, o) end end   Odd_word.main
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.
#Erlang
Erlang
  handle(S, false, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) -> O(S), handle(I(), false, I, O); handle(S, T, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) -> D = handle(I(), rec, I, O), O(S), case T of true -> handle(D, T, I, O); _ -> D end; handle(S, rec, _, _) -> S; handle($., _, _, O) -> O($.), done; handle(eof, _, _, _) -> done; handle(S, T, I, O) -> O(S), handle(I(), not T, I, O).   main([]) -> I = fun() -> hd(io:get_chars([], 1)) end, O = fun(S) -> io:put_chars([S]) end, handle(I(), false, I, O).  
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
#Action.21
Action!
PROC KnuthShuffle(BYTE ARRAY tab BYTE size) BYTE i,j,tmp   i=size-1 WHILE i>0 DO j=Rand(i+1) tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==-1 OD RETURN   BYTE FUNC IsSorted(BYTE ARRAY tab BYTE size) BYTE i   FOR i=0 TO size-2 DO IF tab(i)>tab(i+1) THEN RETURN (0) FI OD RETURN (1)   PROC Swap(BYTE ARRAY tab BYTE size,count) BYTE i,j,tmp   i=0 j=count-1 WHILE i<j DO tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==+1 j==-1 OD RETURN   PROC Main() DEFINE SIZE="9" BYTE ARRAY a(SIZE) BYTE i,j,n,tmp BYTE LMARGIN=$52,oldLMARGIN   oldLMARGIN=LMARGIN LMARGIN=0 ;remove left margin on the screen Put(125) PutE() ;clear the screen   FOR i=0 TO SIZE-1 DO a(i)=i+1 OD KnuthShuffle(a,SIZE)   i=0 DO PrintF("%B: ",i) FOR j=0 TO SIZE-1 DO PrintB(a(j)) OD IF IsSorted(a,SIZE) THEN EXIT FI PrintF(" How many to flip (2-%B)? ",SIZE) n=InputB() IF n>=2 AND n<=SIZE THEN Swap(a,SIZE,n) i==+1 FI OD   PrintF("%E%EYou solved it in %B moves!",i)   LMARGIN=oldLMARGIN ;restore left margin on the screen RETURN
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an 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.
#8th
8th
  null? if "item was null" . then  
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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program nullobj64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" /*******************************************/ /* Initialized data */ /*******************************************/ .data szCarriageReturn: .asciz "\n" szMessResult: .asciz "Value is null.\n" // message result   qPtrObjet: .quad 0 // objet pointer /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   ldr x0,qAdrqPtrObjet // load pointer address ldr x0,[x0] // load pointer value cbnz x0,100f // is null ? ldr x0,qAdrszMessResult // yes -> display message bl affichageMess   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrszMessResult: .quad szMessResult qAdrszCarriageReturn: .quad szCarriageReturn qAdrqPtrObjet: .quad qPtrObjet /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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.
#BASIC256
BASIC256
arraybase 1 dim start = {0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0} dim sgtes(start[?]+1)   for k = 0 to 9 print "Generation "; k; ": "; for j = 0 to start[?]-1   if start[j] then print "#"; else print "_"; if start[j-1] + start[j] + start[j+1] = 2 then sgtes[j] = 1 else sgtes[j] = 0 next j print for j = 0 to start[?]-1 start[j] = sgtes[j] next j next k
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.
#AutoHotkey
AutoHotkey
MsgBox % Rect("fun", 0, 1, 10,-1) ; 0.45 left MsgBox % Rect("fun", 0, 1, 10) ; 0.50 mid MsgBox % Rect("fun", 0, 1, 10, 1) ; 0.55 right MsgBox % Trapez("fun", 0, 1, 10) ; 0.50 MsgBox % Simpson("fun", 0, 1, 10) ; 0.50   Rect(f,a,b,n,side=0) { ; side: -1=left, 0=midpoint, 1=right h := (b - a) / n sum := 0, a += (side-1)*h/2 Loop %n% sum += %f%(a + h*A_Index) Return h*sum }   Trapez(f,a,b,n) { h := (b - a) / n sum := 0 Loop % n-1 sum += %f%(a + h*A_Index) Return h/2 * (%f%(a) + %f%(b) + 2*sum) }   Simpson(f,a,b,n) { h := (b - a) / n sum1 := sum2 := 0, ah := a - h/2 Loop %n% sum1 += %f%(ah + h*A_Index) Loop % n-1 sum2 += %f%(a + h*A_Index) Return h/6 * (%f%(a) + %f%(b) + 4*sum1 + 2*sum2) }   fun(x) { ; linear test function Return x }
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls
Numbers with equal rises and falls
When a number is written in base 10,   adjacent digits may "rise" or "fall" as the number is read   (usually from left to right). Definition Given the decimal digits of the number are written as a series   d:   A   rise   is an index   i   such that   d(i)  <  d(i+1)   A   fall    is an index   i   such that   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
#C.2B.2B
C++
#include <iomanip> #include <iostream>   bool equal_rises_and_falls(int n) { int total = 0; for (int previous_digit = -1; n > 0; n /= 10) { int digit = n % 10; if (previous_digit > digit) ++total; else if (previous_digit >= 0 && previous_digit < digit) --total; previous_digit = digit; } return total == 0; }   int main() { const int limit1 = 200; const int limit2 = 10000000; int n = 0; std::cout << "The first " << limit1 << " numbers in the sequence are:\n"; for (int count = 0; count < limit2; ) { if (equal_rises_and_falls(++n)) { ++count; if (count <= limit1) std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' '); } } std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n"; }
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
#CLU
CLU
% Find how many rises and falls a number has rises_falls = proc (n: int) returns (int,int) rises: int := 0 falls: int := 0   while n >= 10 do dl: int := n//10 n := n / 10 dh: int := n//10 if dh < dl then rises := rises + 1 elseif dl < dh then falls := falls + 1 end end return (rises, falls) end rises_falls   % Generate all numbers with equal rises and falls equal_rises_falls = iter () yields (int) n: int := 1 rises, falls: int while true do rises, falls := rises_falls(n) if rises = falls then yield (n) end n := n + 1 end end equal_rises_falls   % Show the first 200 and the 10,000,000th start_up = proc () po: stream := stream$primary_output() count: int := 0   for n: int in equal_rises_falls() do count := count + 1 if count <= 200 then stream$putright(po, int$unparse(n), 5) if count//10 = 0 then stream$putc(po, '\n') end elseif count = 10000000 then stream$putl(po, "\nThe 10,000,000th number is: " || int$unparse(n)) break end end end start_up