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/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#REXX
REXX
/* REXX *************************************************************** * Merge 1.txt ... n.txt into all.txt * 1.txt 2.txt 3.txt 4.txt * 1 19 1999 2e3 * 17 33 2999 3000 * 8 500 3999 RC task STREAM MERGE **********************************************************************/ done.=0 /* done.i=1 indicates file exhausted */ p.='' /* for test of sort error */ Do i=1 By 1 /* check files for existence */ f.i=i'.txt' If lines(f.i)=0 Then Leave Call get i /* and read first line of each*/ End n=i-1 /* we have n input files */ done.0=n /* and all must be used */ say n 'Input files' oid='all.txt' If lines(oid)>0 Then Do /* output file exists */ Call lineout oid Do Until wordpos(answer,'Y N')>0 Say 'file' oid 'exists. May it be replaced?' Pull answer End If answer='Y' Then 'erase' oid Else Do Say 'Ok, we give up' Exit End End say oid 'is the output file' /* we'll create it now */ Do Until done.0=0 imin=0 /* index of next source */ Do i=1 To n If done.i=0 Then Do /* file i still in use */ If imin=0 Then Do /* it's the first in this loop*/ imin=i /* next source */ min=x.i /* element to be used */ End Else Do /* not the first */ If x.i<<min Then Do /* avoid numerical comparison */ imin=i /* next source */ min=x.i /* element to be used */ End End End End If imin<>0 Then Do /* found next source */ Call o x.imin /* use its element */ Call get imin /* get next element */ /* or set done.imin */ End Else /* no more elements */ Call lineout oid /* close output file */ End 'type' oid Exit   get: Procedure Expose f. x. p. done. /********************************************************************* * Get next element from file ii or set done.ii=1 if file is exhausted *********************************************************************/ Parse Arg ii If lines(f.ii)=0 Then Do /* file ii is exhausted */ done.ii=1 /* mark it as done */ done.0=done.0-1 /* reduce number of files tbd*/ End Else Do /* there's more in file ii */ x.ii=linein(f.ii) /* get next element (line) */ If x.ii<<p.ii Then Do /* smaller than previous */ Say 'Input file' f.ii 'is not sorted ascendingly' Say p.ii 'precedes' x.ii /* tell the user */ Exit /* and give up */ End p.ii=x.ii /* remember the element */ End Return   o: Return lineout(oid,arg(1))
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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
#AppleScript
AppleScript
use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later. use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>   on stateNamePuzzle() script o property stateNames : {"Alabama", "Alaska", "Arizona", "Arkansas", ¬ "California", "Colorado", "Connecticut", "Delaware", ¬ "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", ¬ "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", ¬ "Maine", "Maryland", "Massachusetts", "Michigan", ¬ "Minnesota", "Mississippi", "Missouri", "Montana", ¬ "Nebraska", "Nevada", "New Hampshire", "New Jersey", ¬ "New Mexico", "New York", "North Carolina", "North Dakota", ¬ "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", ¬ "South Carolina", "South Dakota", "Tennessee", "Texas", ¬ "Utah", "Vermont", "Virginia", ¬ "Washington", "West Virginia", "Wisconsin", "Wyoming", ¬ "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"} property namePairs : {} property checkList : {} end script   ignoring case -- Remove duplicates. repeat with i from 1 to (count o's stateNames) set thisName to item i of o's stateNames if (thisName is not in o's checkList) then set end of o's checkList to thisName end repeat set o's stateNames to o's checkList   -- Build lists containing unique pairs of names preceded by -- texts composed of their combined visible characters, sorted. set stateCount to (count o's stateNames) repeat with i from 1 to (stateCount - 1) set name1 to item i of o's stateNames repeat with j from (i + 1) to stateCount set name2 to item j of o's stateNames set chrs to characters of (name1 & name2) tell sorter to sort(chrs, 1, -1, {}) set end of o's namePairs to {word 1 of join(chrs, ""), name1, name2} end repeat end repeat   -- Sort the lists on the character strings set pairCount to (count o's namePairs) tell sorter to sort(o's namePairs, 1, pairCount, {comparer:me})   -- Look for groups of equal character strings and match -- associated name pairs not containing the same name(s). set output to {} set l to 1 repeat while (l < pairCount) set chrs to beginning of item l of o's namePairs set r to l repeat while ((r < pairCount) and (beginning of item (r + 1) of o's namePairs = chrs)) set r to r + 1 end repeat if (r > l) then repeat with i from l to (r - 1) set {name1, name2} to rest of item i of o's namePairs set text1 to join(result, " and ") & " --> " repeat with j from (i + 1) to r set pair2 to rest of item j of o's namePairs if (not ((name1 is in pair2) or (name2 is in pair2))) then set end of output to text1 & join(pair2, " and ") end if end repeat end repeat end if set l to r + 1 end repeat end ignoring   return join(output, linefeed) end stateNamePuzzle   -- Custom comparison handler used when the sort comparer is 'me'. Compares the first items of two lists. on isGreater(a, b) return (beginning of a comes after beginning of b) end isGreater   on join(lst, delim) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to delim set txt to lst as text set AppleScript's text item delimiters to astid return txt end join   stateNamePuzzle()
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#8086_Assembly
8086 Assembly
with Ada.Text_IO; procedure Foo is begin Ada.Text_IO.Put_Line("Bar"); end Foo;
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Ada
Ada
with Ada.Text_IO; procedure Foo is begin Ada.Text_IO.Put_Line("Bar"); end Foo;
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#ALGOL_68
ALGOL 68
BEGIN print( ( "Hello, World!", newline ) ) END
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Arturo
Arturo
main: function [][ print "Yes, we are in main!" ]   main
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#PHP
PHP
$key2val = ["A"=>"30", "B"=>"31", "C"=>"32", "D"=>"33", "E"=>"5", "F"=>"34", "G"=>"35", "H"=>"0", "I"=>"36", "J"=>"37", "K"=>"38", "L"=>"2", "M"=>"4", "."=>"78", "N"=>"39", "/"=>"79", "O"=>"1", "0"=>"790", "P"=>"70", "1"=>"791", "Q"=>"71", "2"=>"792", "R"=>"8", "3"=>"793", "S"=>"6", "4"=>"794", "T"=>"9", "5"=>"795", "U"=>"72", "6"=>"796", "V"=>"73", "7"=>"797", "W"=>"74", "8"=>"798", "X"=>"75", "9"=>"799", "Y"=>"76", "Z"=>"77"];   $val2key = array_flip($key2val);   function encode(string $s) : string { global $key2val;   $callback = function($c) use ($key2val) { return $key2val[$c] ?? ''; };   return implode(array_map($callback, str_split(strtoupper($s)))); }   function decode(string $s) : string { global $val2key;   $callback = function($c) use ($val2key) { return $val2key[$c] ?? ''; };   preg_match_all('/79.|7.|3.|./', $s, $m);   return implode(array_map($callback, $m[0])); }   function main($s) { $encoded = encode($s); echo $encoded; echo "\n"; echo decode($encoded); }   main('One night-it was on the twentieth of March, 1888-I was returning');
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#REXX
REXX
/*REXX program to compute and display (unsigned) Stirling numbers of the first kind.*/ parse arg lim . /*obtain optional argument from the CL.*/ if lim=='' | lim=="," then lim= 12 /*Not specified? Then use the default.*/ olim= lim /*save the original value of LIM. */ lim= abs(lim) /*only use the absolute value of LIM. */ numeric digits max(9, 2*lim) /*(over) specify maximum number in grid*/ @.=; @.0.0= 1 /*define the (0, 0)th value in grid*/ do n=0 for lim+1 /* [↓] initialize some values " " */ if n>0 then @.n.0 = 0 /*assign value if N > zero. */ do k=n+1 to lim @.n.k = 0 /*zero some values in grid if K > N. */ end /*k*/ end /*n*/ max#.= 0 /* [↓] calculate values for the grid. */ do n=1 for lim; nm= n - 1 do k=1 for lim; km= k - 1 @.n.k = @.nm.km + nm * @.nm.k /*calculate an unsigned number in grid.*/ max#.k= max(max#.k, @.n.k) /*find the maximum value " " */ max#.b= max(max#.b, @.n.k) /*find the maximum value for all rows. */ end /*k*/ end /*n*/   do k=1 for lim /*find max column width for each column*/ max#.a= max#.a + length(max#.k) end /*k*/ /* [↓] only show the maximum value ? */ w= length(max#.b) /*calculate max width of all numbers. */ if olim<0 then do; say 'The maximum value (which has ' w " decimal digits):" say max#.b /*display maximum number in the grid. */ exit /*stick a fork in it, we're all done. */ end wi= max(3, length(lim+1) ) /*the maximum width of the grid's index*/ say 'row' center('columns', max(9, max#.a + lim), '═') /*display header of the grid.*/   do r=0 for lim+1; $= /* [↓] display the grid to the term. */ do c=0 for lim+1 until c>=r /*build a row of grid, 1 col at a time.*/ $= $ right(@.r.c, length(max#.c) ) /*append a column to a row of the grid.*/ end /*c*/ say right(r,wi) strip(substr($,2), 'T') /*display a single row of the grid. */ end /*r*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Jsish
Jsish
/* String append, in Jsish */ var str = 'Hello'; ;str += ', world';   var s2 = 'Goodbye'; ;s2.concat(', World!');   /* =!EXPECTSTART!= str += ', world' ==> Hello, world s2.concat(', World!') ==> Goodbye, World! =!EXPECTEND!= */
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Julia
Julia
s = "Hello" s *= ", world!"
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793 Randomize   ' Generates normally distributed random numbers with mean 0 and standard deviation 1 Function randomNormal() As Double Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd)) End Function   Sub normalStats(sampleSize As Integer) If sampleSize < 1 Then Return Dim r(1 To sampleSize) As Double Dim h(-1 To 10) As Integer '' all zero by default Dim sum As Double = 0.0 Dim hSum As Integer = 0   ' Generate 'sampleSize' normally distributed random numbers with mean 0.5 and standard deviation 0.25 ' calculate their sum ' and in which box they will fall when drawing the histogram For i As Integer = 1 To sampleSize r(i) = 0.5 + randomNormal / 4.0 sum += r(i) If r(i) < 0.0 Then h(-1) += 1 ElseIf r(i) >= 1.0 Then h(10) += 1 Else h(Int(r(i) * 10)) += 1 End If Next   For i As Integer = -1 To 10 : hSum += h(i) : Next ' adjust one of the h() values if necessary to ensure hSum = sampleSize Dim adj As Integer = sampleSize - hSum If adj <> 0 Then For i As Integer = -1 To 10 h(i) += adj If h(i) >= 0 Then Exit For h(i) -= adj Next End If   Dim mean As Double = sum / sampleSize   Dim sd As Double sum = 0.0 ' Now calculate their standard deviation For i As Integer = 1 To sampleSize sum += (r(i) - mean) ^ 2.0 Next sd = Sqr(sum/sampleSize)   ' Draw a histogram of the data with interval 0.1 Dim numStars As Integer ' If sample size > 300 then normalize histogram to 300 Dim scale As Double = 1.0 If sampleSize > 300 Then scale = 300.0 / sampleSize Print "Sample size "; sampleSize Print Print Using " Mean #.######"; mean; Print Using " SD #.######"; sd Print For i As Integer = -1 To 10 If i = -1 Then Print Using "< 0.00 : "; ElseIf i = 10 Then Print Using ">=1.00 : "; Else Print Using " #.## : "; i/10.0; End If Print Using "##### " ; h(i); numStars = Int(h(i) * scale + 0.5) Print String(numStars, "*") Next End Sub   normalStats 100 Print normalStats 1000 Print normalStats 10000 Print normalStats 100000 Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146";   int[] ints = data.Split(' ').Select(int.Parse).ToArray();   StemAndLeafPlot(ints);   Console.ReadKey(); }   public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr);   for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     ------------------ STERN-BROCOT SEQUENCE -----------------   -- sternBrocot :: Generator [Int] on sternBrocot() script go on |λ|(xs) set x to snd(xs) tail(xs) & {fst(xs) + x, x} end |λ| end script fmapGen(my head, iterate(go, {1, 1})) end sternBrocot     --------------------------- TEST ------------------------- on run set sbs to take(1200, sternBrocot()) set ixSB to zip(sbs, enumFrom(1))   script low on |λ|(x) 12 ≠ fst(x) end |λ| end script   script sameFst on |λ|(a, b) fst(a) = fst(b) end |λ| end script   script asList on |λ|(x) {fst(x), snd(x)} end |λ| end script   script below100 on |λ|(x) 100 ≠ fst(x) end |λ| end script   script fullyReduced on |λ|(ab) 1 = gcd(|1| of ab, |2| of ab) end |λ| end script   unlines(map(showJSON, ¬ {take(15, sbs), ¬ take(10, map(asList, ¬ nubBy(sameFst, ¬ sortBy(comparing(fst), ¬ takeWhile(low, ixSB))))), ¬ asList's |λ|(fst(take(1, dropWhile(below100, ixSB)))), ¬ all(fullyReduced, take(1000, zip(sbs, tail(sbs))))})) end run   --> [1,1,2,1,3,2,3,1,4,3,5,2,5,3,4] --> [[1,32],[2,24],[3,40],[4,36],[5,44],[6,33],[7,38],[8,42],[9,35],[10,39]] --> [100,1179] --> true     ------------------------- GENERIC ------------------------   -- Absolute value. -- abs :: Num -> Num on abs(x) if 0 > x then -x else x end if end abs     -- Applied to a predicate and a list, `all` determines if all elements -- of the list satisfy the predicate. -- all :: (a -> Bool) -> [a] -> Bool on all(p, xs) tell mReturn(p) set lng to length of xs repeat with i from 1 to lng if not |λ|(item i of xs, i, xs) then return false end repeat true end tell end all     -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) script on |λ|(a, b) tell mReturn(f) set fa to |λ|(a) set fb to |λ|(b) if fa < fb then -1 else if fa > fb then 1 else 0 end if end tell end |λ| end script end comparing     -- drop :: Int -> [a] -> [a] -- drop :: Int -> String -> String on drop(n, xs) set c to class of xs if c is not script then if c is not string then if n < length of xs then items (1 + n) thru -1 of xs else {} end if else if n < length of xs then text (1 + n) thru -1 of xs else "" end if end if else take(n, xs) -- consumed return xs end if end drop     -- dropWhile :: (a -> Bool) -> [a] -> [a] -- dropWhile :: (Char -> Bool) -> String -> String on dropWhile(p, xs) set lng to length of xs set i to 1 tell mReturn(p) repeat while i ≤ lng and |λ|(item i of xs) set i to i + 1 end repeat end tell drop(i - 1, xs) end dropWhile     -- enumFrom :: a -> [a] on enumFrom(x) script property v : missing value property blnNum : class of x is not text on |λ|() if missing value is not v then if blnNum then set v to 1 + v else set v to succ(v) end if else set v to x end if return v end |λ| end script end enumFrom     -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) tell mReturn(f) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell end filter     -- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] on fmapGen(f, gen) script property g : gen property mf : mReturn(f)'s |λ| on |λ|() set v to g's |λ|() if v is missing value then v else mf(v) end if end |λ| end script end fmapGen     -- fst :: (a, b) -> a on fst(tpl) if class of tpl is record then |1| of tpl else item 1 of tpl end if end fst     -- gcd :: Int -> Int -> Int on gcd(a, b) set x to abs(a) set y to abs(b) repeat until y = 0 if x > y then set x to x - y else set y to y - x end if end repeat return x end gcd     -- head :: [a] -> a on head(xs) if xs = {} then missing value else item 1 of xs end if end head     -- iterate :: (a -> a) -> a -> Gen [a] on iterate(f, x) script property v : missing value property g : mReturn(f)'s |λ| on |λ|() if missing value is v then set v to x else set v to g(v) end if return v end |λ| end script end iterate     -- length :: [a] -> Int on |length|(xs) set c to class of xs if list is c or string is c then length of xs else (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite) end if end |length|     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- nubBy :: (a -> a -> Bool) -> [a] -> [a] on nubBy(f, xs) set g to mReturn(f)'s |λ|   script notEq property fEq : g on |λ|(a) script on |λ|(b) not fEq(a, b) end |λ| end script end |λ| end script   script go on |λ|(xs) if (length of xs) > 1 then set x to item 1 of xs {x} & go's |λ|(filter(notEq's |λ|(x), items 2 thru -1 of xs)) else xs end if end |λ| end script   go's |λ|(xs) end nubBy     -- partition :: predicate -> List -> (Matches, nonMatches) -- partition :: (a -> Bool) -> [a] -> ([a], [a]) on partition(f, xs) tell mReturn(f) set ys to {} set zs to {} repeat with x in xs set v to contents of x if |λ|(v) then set end of ys to v else set end of zs to v end if end repeat end tell Tuple(ys, zs) end partition     -- showJSON :: a -> String on showJSON(x) set c to class of x if (c is list) or (c is record) then set ca to current application set {json, e} to ca's NSJSONSerialization's dataWithJSONObject:x options:0 |error|:(reference) if json is missing value then e's localizedDescription() as text else (ca's NSString's alloc()'s initWithData:json encoding:(ca's NSUTF8StringEncoding)) as text end if else if c is date then "\"" & ((x - (time to GMT)) as «class isot» as string) & ".000Z" & "\"" else if c is text then "\"" & x & "\"" else if (c is integer or c is real) then x as text else if c is class then "null" else try x as text on error ("«" & c as text) & "»" end try end if end showJSON     -- snd :: (a, b) -> b on snd(tpl) if class of tpl is record then |2| of tpl else item 2 of tpl end if end snd     -- Enough for small scale sorts. -- Use instead sortOn :: Ord b => (a -> b) -> [a] -> [a] -- which is equivalent to the more flexible sortBy(comparing(f), xs) -- and uses a much faster ObjC NSArray sort method -- sortBy :: (a -> a -> Ordering) -> [a] -> [a] on sortBy(f, xs) if length of xs > 1 then set h to item 1 of xs set f to mReturn(f) script on |λ|(x) f's |λ|(x, h) ≤ 0 end |λ| end script set lessMore to partition(result, rest of xs) sortBy(f, |1| of lessMore) & {h} & ¬ sortBy(f, |2| of lessMore) else xs end if end sortBy     -- tail :: [a] -> [a] on tail(xs) set blnText to text is class of xs if blnText then set unit to "" else set unit to {} end if set lng to length of xs if 1 > lng then missing value else if 2 > lng then unit else if blnText then text 2 thru -1 of xs else rest of xs end if end if end tail     -- take :: Int -> [a] -> [a] -- take :: Int -> String -> String on take(n, xs) set c to class of xs if list is c then if 0 < n then items 1 thru min(n, length of xs) of xs else {} end if else if string is c then if 0 < n then text 1 thru min(n, length of xs) of xs else "" end if else if script is c then set ys to {} repeat with i from 1 to n set v to xs's |λ|() if missing value is v then return ys else set end of ys to v end if end repeat return ys else missing value end if end take     -- takeWhile :: (a -> Bool) -> [a] -> [a] -- takeWhile :: (Char -> Bool) -> String -> String on takeWhile(p, xs) if script is class of xs then takeWhileGen(p, xs) else tell mReturn(p) repeat with i from 1 to length of xs if not |λ|(item i of xs) then ¬ return take(i - 1, xs) end repeat end tell return xs end if end takeWhile     -- takeWhileGen :: (a -> Bool) -> Gen [a] -> [a] on takeWhileGen(p, xs) set ys to {} set v to |λ|() of xs tell mReturn(p) repeat while (|λ|(v)) set end of ys to v set v to xs's |λ|() end repeat end tell return ys end takeWhileGen     -- Tuple (,) :: a -> b -> (a, b) on Tuple(a, b) {type:"Tuple", |1|:a, |2|:b, length:2} end Tuple     -- unlines :: [String] -> String on unlines(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines     -- zip :: [a] -> [b] -> [(a, b)] on zip(xs, ys) zipWith(Tuple, xs, ys) end zip     -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(|length|(xs), |length|(ys)) if 1 > lng then return {} set xs_ to take(lng, xs) -- Allow for non-finite set ys_ to take(lng, ys) -- generators like cycle etc set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs_, item i of ys_) end repeat return lst end tell end zipWith
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Raku
Raku
sub merge_streams ( @streams ) { my @s = @streams.map({ hash( STREAM => $_, HEAD => .get ) })\ .grep({ .<HEAD>.defined });   return gather while @s { my $h = @s.min: *.<HEAD>; take $h<HEAD>; $h<HEAD> := $h<STREAM>.get orelse @s .= grep( { $_ !=== $h } ); } }   say merge_streams([ @*ARGS».&open ]);
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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
#Bracmat
Bracmat
( Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada "New Hampshire" "New Jersey" "New Mexico" "New York" "North Carolina" "North Dakota" Ohio Oklahoma Oregon Pennsylvania "Rhode Island" "South Carolina" "South Dakota" Tennessee Texas Utah Vermont Virginia Washington "West Virginia" Wisconsin Wyoming  : ?states & "New Kory" "Wen Kory" "York New" "Kory New" "New Kory":?extrastates & ( "State name puzzle" = allStates State state statechars char , A Z S1 S2 S3 S4 L1 L2 L3 L4 L12 . 0:?allStates & whl ' ( !arg:%?State ?arg & low$!State:?state & 0:?statechars & whl ' ( @(!state:? (%@:~" ":?char) ?state) & !char+!statechars:?statechars ) & (!State.!statechars)+!allStates:?allStates ) & (  !allStates  :  ? + ?*(?S1.?L1) + ?A + ?*(?S2.?L2) + ( ?Z & !L1+!L2:?L12 &  !A+!Z  :  ? + ?*(?S3.?L3&!L12+-1*!L3:?L4) + ? +  ? * ( ?S4 .  !L4 & out$(!S1 "+" !S2 "=" !S3 "+" !S4) & ~ ) + ? ) | out$"No more solutions" ) ) & "State name puzzle"$!states & "State name puzzle"$(!states !extrastates) );
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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> #include <stdlib.h> #include <string.h>   #define USE_FAKES 1   const char *states[] = { #if USE_FAKES "New Kory", "Wen Kory", "York New", "Kory New", "New Kory", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" };   int n_states = sizeof(states)/sizeof(*states); typedef struct { unsigned char c[26]; const char *name[2]; } letters;   void count_letters(letters *l, const char *s) { int c; if (!l->name[0]) l->name[0] = s; else l->name[1] = s;   while ((c = *s++)) { if (c >= 'a' && c <= 'z') l->c[c - 'a']++; if (c >= 'A' && c <= 'Z') l->c[c - 'A']++; } }   int lcmp(const void *aa, const void *bb) { int i; const letters *a = aa, *b = bb; for (i = 0; i < 26; i++) if (a->c[i] > b->c[i]) return 1; else if (a->c[i] < b->c[i]) return -1; return 0; }   int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }   void no_dup() { int i, j;   qsort(states, n_states, sizeof(const char*), scmp);   for (i = j = 0; i < n_states;) { while (++i < n_states && !strcmp(states[i], states[j])); if (i < n_states) states[++j] = states[i]; }   n_states = j + 1; }   void find_mix() { int i, j, n; letters *l, *p;   no_dup(); n = n_states * (n_states - 1) / 2; p = l = calloc(n, sizeof(letters));   for (i = 0; i < n_states; i++) for (j = i + 1; j < n_states; j++, p++) { count_letters(p, states[i]); count_letters(p, states[j]); }   qsort(l, n, sizeof(letters), lcmp);   for (j = 0; j < n; j++) { for (i = j + 1; i < n && !lcmp(l + j, l + i); i++) { if (l[j].name[0] == l[i].name[0] || l[j].name[1] == l[i].name[0] || l[j].name[1] == l[i].name[1]) continue; printf("%s + %s => %s + %s\n", l[j].name[0], l[j].name[1], l[i].name[0], l[i].name[1]); } } free(l); }   int main(void) { find_mix(); return 0; }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#AutoHotkey
AutoHotkey
BEGIN { # This is our main startup procedure print "Hello World!" }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#AWK
AWK
BEGIN { # This is our main startup procedure print "Hello World!" }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#BASIC
BASIC
SUB main PRINT "Hello from main!" END SUB   main
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#C
C
  #include<stdio.h>   #define start main()   int start { printf("Hello World !"); return 0; }  
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#PicoLisp
PicoLisp
(de *Straddling (NIL "H" "O" "L" NIL "M" "E" "S" NIL "R" "T") ("3" "A" "B" "C" "D" "F" "G" "I" "J" "K" "N") ("7" "P" "Q" "U" "V" "W" "X" "Y" "Z" "." "/") ("79" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9") )   (de straddle (Str) (pack (mapcar '((C) (pick '((L) (and (index C (cdr L)) (cons (car L) (dec @)) ) ) *Straddling ) ) (chop (uppc Str)) ) ) )   (de unStraddle (Str) (pack (make (for (L (chop Str) L) (let C (pop 'L) (setq C (if (assoc C *Straddling) (get (cdr @) (inc (format (pop 'L)))) (get (cdar *Straddling) (inc (format C))) ) ) (link (if (= "/" C) (pop 'L) C)) ) ) ) ) )
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#PureBasic
PureBasic
Procedure.s encrypt_SC(originalText.s, alphabet.s, blank_1, blank_2) Static notEscape.s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." Protected preDigit_1.s = Str(blank_1), preDigit_2.s = Str(blank_2) Protected i, index, curChar.s, escapeChar.s, outputText.s Protected NewMap cipher.s()   ;build cipher reference alphabet = UCase(alphabet) For i = 1 To 28 curChar = Mid(alphabet, i, 1) If Not FindString(notEscape, curChar) escapeChar = curChar EndIf   Select i Case 1 To 8 If index = blank_1 Or index = blank_2: index + 1: EndIf ;adjust index for blank   cipher(curChar) = Str(index) index + 1 Case 9 To 18 cipher(curChar) = preDigit_1 + Str(i - 9) Case 19 To 28 cipher(curChar) = preDigit_2 + Str(i - 19) EndSelect Next   For i = 0 To 9: cipher(Str(i)) = cipher(escapeChar) + Str(i): Next   ;encrypt each character originalText = UCase(originalText) Protected length = Len(originalText) For i = 1 To length outputText + cipher(Mid(originalText, i, 1)) Next   ProcedureReturn outputText EndProcedure   Procedure.s decrypt_SC(cipherText.s, alphabet.s, blank_1, blank_2) Static notEscape.s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." Protected preDigit_1.s = Str(blank_1), preDigit_2.s = Str(blank_2) Protected i, index, curChar.s, escapeCipher.s, outputText.s Protected NewMap cipher.s()   ;build decipher reference alphabet = UCase(alphabet) For i = 1 To 28 curChar = Mid(alphabet, i, 1)   Select i Case 1 To 8 If index = blank_1 Or index = blank_2: index + 1: EndIf ;adjust index for blank   cipher(Str(index)) = curChar index + 1 Case 9 To 18 cipher(preDigit_1 + Str(i - 9)) = curChar Case 19 To 28 cipher(preDigit_2 + Str(i - 19)) = curChar EndSelect If Not FindString(notEscape, curChar) escapeCipher = MapKey(cipher()) EndIf Next   For i = 0 To 9: cipher(escapeCipher + Str(i)) = Str(i): Next   ;decrypt each character Protected length = Len(cipherText) index = 1 While index <=length curChar = Mid(cipherText, index, 1) If curChar = preDigit_1 Or curChar = preDigit_2 curChar = Mid(cipherText, index, 2) If curChar = escapeCipher: curChar = Mid(cipherText, index, 3): EndIf EndIf outputText + cipher(curChar) index + Len(curChar) Wend   ProcedureReturn outputText EndProcedure   If OpenConsole() Define message.s = "One night-it was on the twentieth of March, 1888-I was returning" Define cipher.s = "HOLMESRTABCDFGIJKNPQUVWXYZ./", encoded.s   PrintN("Original: " + message) encoded = encrypt_SC(message, cipher, 3, 7) PrintN("encoded: " + encoded) PrintN("decoded: " + decrypt_SC(encoded, cipher, 3, 7))   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#Ruby
Ruby
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) $cache[key] = value return value end   MAX = 12 def main print "Unsigned Stirling numbers of the first kind:\n" print "n/k" for n in 0 .. MAX print "%10d" % [n] end print "\n"   for n in 0 .. MAX print "%-3d" % [n] for k in 0 .. n print "%10d" % [sterling1(n, k)] end print "\n" end   print "The maximum value of S1(100, k) =\n" previous = 0 for k in 1 .. 100 current = sterling1(100, k) if previous < current then previous = current else print previous, "\n" print "(%d digits, k = %d)\n" % [previous.to_s.length, k - 1] break end end end   main()
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Kotlin
Kotlin
fun main(args: Array<String>) { var s = "a" s += "b" s += "c" println(s) println("a" + "b" + "c") val a = "a" val b = "b" val c = "c" println("$a$b$c") }
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Lambdatalk
Lambdatalk
  {def christian_name Albert} -> christian_name {def name de Jeumont-Schneidre} -> name   {christian_name} {name} -> Albert de Jeumont-Schneidre  
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#langur
langur
var .s = "no more " .s ~= "foo bars" writeln .s
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#Go
Go
package main   import ( "fmt" "math" "math/rand" "strings" )   // Box-Muller func norm2() (s, c float64) { r := math.Sqrt(-2 * math.Log(rand.Float64())) s, c = math.Sincos(2 * math.Pi * rand.Float64()) return s * r, c * r }   func main() { const ( n = 10000 bins = 12 sig = 3 scale = 100 ) var sum, sumSq float64 h := make([]int, bins) for i, accum := 0, func(v float64) { sum += v sumSq += v * v b := int((v + sig) * bins / sig / 2) if b >= 0 && b < bins { h[b]++ } }; i < n/2; i++ { v1, v2 := norm2() accum(v1) accum(v2) } m := sum / n fmt.Println("mean:", m) fmt.Println("stddev:", math.Sqrt(sumSq/float64(n)-m*m)) for _, p := range h { fmt.Println(strings.Repeat("*", p/scale)) } }
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#C.2B.2B
C++
#include <algorithm> #include <iomanip> #include <iostream> #include <vector>   const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]);   int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot;   for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); }   std::sort(stemplot.begin(), stemplot.end()); // order stem/leaf pairs   int lo = stemplot.front().first; // minimum stem value int hi = stemplot.back().first; // maximum stem value   for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; // print stem   // while (there are more stems) and (stem is equal to lo) for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; // print leaf }   std::cout << std::endl; } }
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#AutoHotkey
AutoHotkey
Found := FindOneToX(100), FoundList := "" Loop, 10 FoundList .= "First " A_Index " found at " Found[A_Index] "`n" MsgBox, 64, Stern-Brocot Sequence , % "First 15: " FirstX(15) "`n" . FoundList . "First 100 found at " Found[100] "`n" . "GCDs of all two consecutive members are " (GCDsUpToXAreOne(1000) ? "" : "not ") "one." return   class SternBrocot { __New() { this[1] := 1 this[2] := 1 this.Consider := 2 }   InsertPair() { n := this.Consider this.Push(this[n] + this[n - 1], this[n]) this.Consider++ } }   ; Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, ; 5, 2, 5, 3, 4) FirstX(x) { SB := new SternBrocot() while SB.MaxIndex() < x SB.InsertPair() Loop, % x Out .= SB[A_Index] ", " return RTrim(Out, " ,") }   ; Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. ; Show the (1-based) index of where the number 100 first appears in the sequence. FindOneToX(x) { SB := new SternBrocot(), xRequired := x, Found := [] while xRequired > 0 ; While the count of numbers yet to be found is > 0. { Loop, 2 ; Consider the second last member and then the last member. { n := SB[i := SB.MaxIndex() - 2 + A_Index] ; If number (n) has not been found yet, and it is less than the maximum number to ; find (x), record the index (i) and decrement the count of numbers yet to be found. if (Found[n] = "" && n <= x) Found[n] := i, xRequired-- } SB.InsertPair() ; Insert the two members that will be checked next. } return Found }   ; Check that the greatest common divisor of all the two consecutive members of the series up to ; the 1000th member, is always one. GCDsUpToXAreOne(x) { SB := new SternBrocot() while SB.MaxIndex() < x SB.InsertPair() Loop, % x - 1 if GCD(SB[A_Index], SB[A_Index + 1]) > 1 return 0 return 1 }   GCD(a, b) { while b b := Mod(a | 0x0, a := b) return a }
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Ruby
Ruby
def stream_merge(*files) fio = files.map{|fname| open(fname)} merge(fio.map{|io| [io, io.gets]}) end   def merge(fdata) until fdata.empty? io, min = fdata.min_by{|_,data| data} puts min if (next_data = io.gets).nil? io.close fdata.delete([io, min]) else i = fdata.index{|x,_| x == io} fdata[i] = [io, next_data] end end end   files = %w(temp1.dat temp2.dat temp3.dat) files.each do |fname| data = IO.read(fname).gsub("\n", " ") puts "#{fname}: #{data}" end stream_merge(*files)
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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.2B.2B
C++
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector>   template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()); return retval; }   #define USE_FAKES 1   auto states = unique(std::vector<std::string>({ #if USE_FAKES "Slender Dragon", "Abalamara", #endif "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" }));   struct counted_pair { std::string name; std::array<int, 26> count{};   void count_characters(const std::string& s) { for (auto&& c : s) { if (c >= 'a' && c <= 'z') count[c - 'a']++; if (c >= 'A' && c <= 'Z') count[c - 'A']++; } }   counted_pair(const std::string& s1, const std::string& s2) : name(s1 + " + " + s2) { count_characters(s1); count_characters(s2); } };   bool operator<(const counted_pair& lhs, const counted_pair& rhs) { auto lhs_size = lhs.name.size(); auto rhs_size = rhs.name.size(); return lhs_size == rhs_size ? std::lexicographical_compare(lhs.count.begin(), lhs.count.end(), rhs.count.begin(), rhs.count.end()) : lhs_size < rhs_size; }   bool operator==(const counted_pair& lhs, const counted_pair& rhs) { return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count; }   int main() { const int n_states = states.size();   std::vector<counted_pair> pairs; for (int i = 0; i < n_states; i++) { for (int j = 0; j < i; j++) { pairs.emplace_back(counted_pair(states[i], states[j])); } } std::sort(pairs.begin(), pairs.end());   auto start = pairs.begin(); while (true) { auto match = std::adjacent_find(start, pairs.end()); if (match == pairs.end()) { break; } auto next = match + 1; std::cout << match->name << " => " << next->name << "\n"; start = next; } }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Clojure
Clojure
  MODULE MainProcedure; IMPORT StdLog;   PROCEDURE Do*; BEGIN StdLog.String("From Do");StdLog.Ln END Do;   PROCEDURE Main*; BEGIN StdLog.String("From Main");StdLog.Ln END Main; END MainProcedure.    
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Component_Pascal
Component Pascal
  MODULE MainProcedure; IMPORT StdLog;   PROCEDURE Do*; BEGIN StdLog.String("From Do");StdLog.Ln END Do;   PROCEDURE Main*; BEGIN StdLog.String("From Main");StdLog.Ln END Main; END MainProcedure.    
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Erlang
Erlang
USE: io IN: example   : hello ( -- ) "Hello, world!" print ;   MAIN: hello
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Factor
Factor
USE: io IN: example   : hello ( -- ) "Hello, world!" print ;   MAIN: hello
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#Python
Python
T = [["79", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["", "H", "O", "L", "", "M", "E", "S", "", "R", "T"], ["3", "A", "B", "C", "D", "F", "G", "I", "J", "K", "N"], ["7", "P", "Q", "U", "V", "W", "X", "Y", "Z", ".", "/"]]   def straddle(s): return "".join(L[0]+T[0][L.index(c)] for c in s.upper() for L in T if c in L)   def unstraddle(s): s = iter(s) for c in s: if c in [T[2][0], T[3][0]]: i = [T[2][0], T[3][0]].index(c) n = T[2 + i][T[0].index(s.next())] yield s.next() if n == "/" else n else: yield T[1][T[0].index(c)]   O = "One night-it was on the twentieth of March, 1888-I was returning" print "Encoded:", straddle(O) print "Decoded:", "".join(unstraddle(straddle(O)))
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#Sidef
Sidef
func S1(n, k) { # unsigned Stirling numbers of the first kind stirling(n, k).abs }   const r = (0..12)   var triangle = r.map {|n| 0..n -> map {|k| S1(n, k) } } var widths = r.map {|n| r.map {|k| (triangle[k][n] \\ 0).len }.max }   say ('n\k ', r.map {|n| "%*s" % (widths[n], n) }.join(' '))   r.each {|n| var str = ('%-3s ' % n) str += triangle[n].map_kv {|k,v| "%*s" % (widths[k], v) }.join(' ') say str }   with (100) {|n| say "\nMaximum value from the S1(#{n}, *) row:" say { S1(n, _) }.map(^n).max }
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#Tcl
Tcl
proc US1 {n k} { if {$k == 0} { return [expr {$n == 0}] } if {$n < $k} { return 0 } if {$n == $k} { return 1 }   set nk [list $n $k] if {[info exists ::US1cache($nk)]} { return $::US1cache($nk) } set n1 [expr {$n - 1}] set k1 [expr {$k - 1}] set r [expr {($n1 * [US1 $n1 $k]) + [US1 $n1 $k1]}]   set ::US1cache($nk) $r }   proc main {} { puts "Unsigned Stirling numbers of the first kind:" set max 12 ;# last table line to print set L 9 ;# space to use for 1 number puts -nonewline "n\\k" for {set n 0} {$n <= $max} {incr n} { puts -nonewline " [format %${L}d $n]" } puts "" for {set n 0} {$n <= $max} {incr n} { puts -nonewline [format %-3d $n] for {set k 0} {$k <= $n} {incr k} { puts -nonewline " [format %${L}s [US1 $n $k]]" } puts "" } puts "The maximum value of US1(100, k) = " set previous 0 for {set k 1} {$k <= 100} {incr k} { set current [US1 100 $k] if {$current > $previous} { set previous $current } else { puts $previous puts "([string length $previous] digits, k = [expr {$k-1}])" break } } } main
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Lasso
Lasso
local(x = 'Hello') #x->append(', World!') #x
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Lingo
Lingo
str = "Hello" put " world!" after str put str -- "Hello world!"
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#LiveCode
LiveCode
local str="live" put "code" after str
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#Haskell
Haskell
import Data.Map (Map, empty, insert, findWithDefault, toList) import Data.Maybe (fromMaybe) import Text.Printf (printf) import Data.Function (on) import Data.List (sort, maximumBy, minimumBy) import Control.Monad.Random (RandomGen, Rand, evalRandIO, getRandomR) import Control.Monad (replicateM)   -- Box-Muller getNorm :: RandomGen g => Rand g Double getNorm = do u0 <- getRandomR (0.0, 1.0) u1 <- getRandomR (0.0, 1.0) let r = sqrt $ (-2.0) * log u0 theta = 2.0 * pi * u1 return $ r * sin theta   putInBin :: Double -> Map Int Int -> Double -> Map Int Int putInBin binWidth t v = let bin = round (v / binWidth) count = findWithDefault 0 bin t in insert bin (count+1) t   runTest :: Int -> IO () runTest n = do rs <- evalRandIO $ replicateM n getNorm let binWidth = 0.1   tally v (sv, sv2, t) = (sv+v, sv2 + v*v, putInBin binWidth t v)   (sum, sum2, tallies) = foldr tally (0.0, 0.0, empty) rs   tallyList = sort $ toList tallies   printStars tallies binWidth maxCount selection = let count = findWithDefault 0 selection tallies bin = binWidth * fromIntegral selection maxStars = 100 starCount = if maxCount <= maxStars then count else maxStars * count `div` maxCount stars = replicate starCount '*' in printf "%5.2f: %s  %d\n" bin stars count   mean = sum / fromIntegral n stddev = sqrt (sum2/fromIntegral n - mean*mean)   printf "\n" printf "sample count: %d\n" n printf "mean:  %9.7f\n" mean printf "stddev:  %9.7f\n" stddev   let maxCount = snd $ maximumBy (compare `on` snd) tallyList maxBin = fst $ maximumBy (compare `on` fst) tallyList minBin = fst $ minimumBy (compare `on` fst) tallyList   mapM_ (printStars tallies binWidth maxCount) [minBin..maxBin]   main = do runTest 1000 runTest 2000000
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#Ceylon
Ceylon
"Run the module `thestemandleafplot`." shared void run() {   value data ="12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146";   value numbers = data .split() .map(parseInteger) .coalesced;   value stemsToLeaves = numbers .group((Integer element) => element / 10) .mapItems((Integer key, [Integer+] item) => item.map((Integer element) => element % 10)) .mapItems((Integer key, {Integer+} item) => sort(item));   value lastStem = stemsToLeaves.keys.last else 0; for(i in 0..lastStem) { print("``formatInteger(i).padLeading(2)``| ``" ".join(stemsToLeaves[i] else [])``"); } }
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#BASIC
BASIC
10 DEFINT A,B,I,J,S: DIM S(1200) 20 S(1)=1: S(2)=1 30 FOR I=2 TO 600 40 S(I*2-1)=S(I)+S(I-1) 50 S(I*2)=S(I) 60 NEXT I 70 PRINT "First 15 elements: "; 80 FOR I=1 TO 15: PRINT USING"# ";S(I);: NEXT I 85 PRINT 90 FOR I=1 TO 10 100 FOR J=1 TO 1200: IF S(J)<>I THEN NEXT J 110 PRINT "First";I;"at";J 120 NEXT I 130 FOR J=1 TO 1200: IF S(J)<>100 THEN NEXT J 140 PRINT "First 100 at";J 150 FOR I=2 TO 1000 160 A=S(I): B=S(I-1) 170 J=A: A=B: B=J MOD A: IF B THEN 170 180 IF A<>1 THEN PRINT "GCD <> 1 at ";I: STOP 190 NEXT I 200 PRINT "All GCDs are 1." 210 END
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Scala
Scala
def mergeN[A : Ordering](is: Iterator[A]*): Iterator[A] = is.reduce((a, b) => merge2(a, b))   def merge2[A : Ordering](i1: Iterator[A], i2: Iterator[A]): Iterator[A] = { merge2Buffered(i1.buffered, i2.buffered) }   def merge2Buffered[A](i1: BufferedIterator[A], i2: BufferedIterator[A])(implicit ord: Ordering[A]): Iterator[A] = { if (!i1.hasNext) { i2 } else if (!i2.hasNext) { i1 } else { val nextHead = if (ord.lt(i1.head, i2.head)) { Iterator.single(i1.next) } else { Iterator.single(i2.next) } nextHead ++ merge2Buffered(i1, i2) } }
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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
#Clojure
Clojure
(ns clojure-sandbox.statenames (:require [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.string :refer [lower-case]] [clojure.math.combinatorics :as c] [clojure.pprint :as pprint]))   (def made-up-states ["New Kory" "Wen Kory" "York New" "Kory New" "New Kory"])   ;; I saved the list of states in a local file to keep the code clean but you can copy and paste the list instead (def real-states (with-open [in-file (io/reader (io/resource "states.csv"))] (->> (doall (csv/read-csv in-file)) (map first))))   (defn- state->charset [state-name] "Convert state name into sorted list of characters with no spaces" (->> state-name char-array sort (filter (set (map char (range 97 123)))))) ;; ASCII range for lower case letters   (defn- add-charsets [states] "Calculate sorted character list for each state and store with name" (->> states (map lower-case) ;; Convert all names to lower case set ;; remove duplicates (map (fn [s] {:name s  :characters (state->charset s)})))) ;; add characters   (defn- pair-chars [state1 state2] "Join the characters of two states together and sort them" (-> state1  :characters (concat (:characters state2)) sort))   (defn- pair [[state1 state2]] "Record representing two state names and the total characters used in them" {:inputs [(:name state1) (:name state2)]  :characters (pair-chars state1 state2)})   (defn- find-all-pairs [elements] (c/combinations elements 2))   (defn- pairs-to-search [state-names] "Create character lists for all states and return a list of all possible pairs" (->> state-names add-charsets find-all-pairs (map pair)))   (defn- pairs-have-same-letters? [[pair1 pair2]] (= (:characters pair1) (:characters pair2)))   (defn- inputs-are-distinct? [[pair1 pair2 :as pairs]] "Check that two pairs of states don't contain the same state" (= 4 ;; There should be a total of 4 distinct states in the two pairs (->> pairs (map :inputs) flatten set count)))   (defn- search [pairs] (->> pairs find-all-pairs ;; find pairs of pairs to search (filter pairs-have-same-letters?) ;; Keep only those where each pair has the same characters (filter inputs-are-distinct?))) ;; Remove pairs with duplicate states   (defn find-matches [state-names] "Find all state pairs and return pairs of them using the same letters" (-> state-names pairs-to-search search))   (defn- format-match-output [[pair1 pair2]] "Format a pair of state pairs to print out" (str (first (:inputs pair1)) " + " (last (:inputs pair1)) " = " (first (:inputs pair2)) " + " (last (:inputs pair2))))   (defn- evaluate-and-print [states] (->> states find-matches (map format-match-output) pprint/pprint))   (defn -main [& args] (println "Solutions for 50 real states") (evaluate-and-print real-states) (println "Solutions with made up states added") (evaluate-and-print (concat real-states made-up-states)))  
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Forth
Forth
include foo.fs ... : main ... ;   main bye
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub main() Print "Hello from main!" End Sub   main Sleep
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Gambas
Gambas
PUBLIC SUB Main() ' This is the start of the program END
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Go
Go
package main   import "fmt"   var count = 0   func foo() { fmt.Println("foo called") }   func init() { fmt.Println("first init called") foo() }   func init() { fmt.Println("second init called") main() }   func main() { count++ fmt.Println("main called when count is", count) }
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#Racket
Racket
#lang racket   (struct *straddling (header main original) #:reflection-name 'straddling #:methods gen:custom-write [(define (write-proc board port mode) (write-string "#<straddling " port) (write (*straddling-original board) port) (write-string ">" port))])   (define string->vector (compose list->vector string->list))   (define (straddling . lines) (define header-tail (reverse (for/fold ([rev-ret '()]) ([char (in-list (string->list (car lines)))] [i (in-naturals)]) (if (equal? char #\space) (cons (number->string i) rev-ret) rev-ret)))) (define main (list->vector (map string->vector (cons "0123456789" (map string-upcase lines))))) (define temporal-board (*straddling (list->vector (list* "?" "" header-tail)) main lines)) (define escape (straddling-encode-char #\/ temporal-board)) (*straddling (list->vector (list* escape "" header-tail)) main lines))
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#Raku
Raku
class Straddling_Checkerboard { has @!flat_board; # 10x3 stored as 30x1 has $!plain2code; # full translation table, invertable has @!table; # Printable layout, like Wikipedia entry   my $numeric_escape = '/'; my $exclude = /<-[A..Z0..9.]>/; # Omit the escape character   method display_table { gather { take ~ .list for @!table } };   method decode ( Str $s --> Str ) { $s.trans($!plain2code.antipairs); }   method encode ( Str $s, :$collapse? --> Str ) { my $replace = $collapse ?? '' !! '.'; $s.uc.subst( $exclude, $replace, :g ).trans($!plain2code); }   submethod BUILD ( :$alphabet, :$u where 0..9, :$v where 0..9 ) { die if $u == $v; die if $alphabet.comb.sort.join ne [~] flat './', 'A'..'Z';   @!flat_board = $alphabet.uc.comb; @!flat_board.splice( $u min $v, 0, Any ); @!flat_board.splice( $u max $v, 0, Any );   @!table = [ ' ',| [ 0 .. 9] ], [ ' ',|@!flat_board[ 0 .. 9].map: {.defined ?? $_ !! ' '} ], [ $u, |@!flat_board[10 .. 19] ], [ $v, |@!flat_board[20 .. 29] ];   my @order = 0..9; # This may be passed as a param in the future   my @nums = flat @order, @order.map({ +"$u$_" }), @order.map({ +"$v$_" });   my %c2p = @nums Z=> @!flat_board; %c2p{$_}:delete if %c2p{$_} eqv Any for keys %c2p; my %p2c = %c2p.invert; %p2c{$_} = %p2c{$numeric_escape} ~ $_ for 0..9; $!plain2code = [%p2c.keys] => [%p2c.values]; } }   sub MAIN ( :$u = 3, :$v = 7, :$alphabet = 'HOLMESRTABCDFGIJKNPQUVWXYZ./' ) { my Straddling_Checkerboard $sc .= new: :$u, :$v, :$alphabet; $sc.display_table;   for 0..1 -> $collapse { my $original = 'One night-it was on the twentieth of March, 1888-I was returning'; my $en = $sc.encode($original, :$collapse); my $de = $sc.decode($en); say ''; say "Original: $original"; say "Encoded: $en"; say "Decoded: $de"; } }
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var computed = {}   var stirling1 // recursive stirling1 = Fn.new { |n, k| var key = "%(n),%(k)" if (computed.containsKey(key)) return computed[key] if (n == 0 && k == 0) return BigInt.one if (n > 0 && k == 0) return BigInt.zero if (k > n) return BigInt.zero var result = stirling1.call(n-1, k-1) + stirling1.call(n-1, k)*(n-1) computed[key] = result return result }   System.print("Unsigned Stirling numbers of the first kind:") var max = 12 System.write("n/k") for (n in 0..max) Fmt.write("$10d", n) System.print() for (n in 0..max) { Fmt.write("$-3d", n) for (k in 0..n) Fmt.write("$10i", stirling1.call(n, k)) System.print() } System.print("The maximum value of S1(100, k) =") var previous = BigInt.zero for (k in 1..100) { var current = stirling1.call(100, k) if (current > previous) { previous = current } else { Fmt.print("$i\n($d digits, k = $d)", previous, previous.toString.count, k - 1) break } }
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Lua
Lua
function string:show () print(self) end   function string:append (s) self = self .. s end   x = "Hi " x:show() x:append("there!") x:show()
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#M2000_Interpreter
M2000 Interpreter
  a$="ok" a$+="(one)" Print a$   Document b$ b$="ok" b$="(one)" Print b$  
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#J
J
runif01=: ?@$ 0: NB. random uniform number generator rnorm01=. (2 o. 2p1 * runif01) * [: %: _2 * ^.@runif01 NB. random normal number generator (Box-Muller)   mean=: +/ % # NB. mean stddev=: (<:@# %~ +/)&.:*:@(- mean) NB. standard deviation histogram=: <:@(#/.~)@(i.@#@[ , I.)
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#Java
Java
import static java.lang.Math.*; import static java.util.Arrays.stream; import java.util.Locale; import java.util.function.DoubleSupplier; import static java.util.stream.Collectors.joining; import java.util.stream.DoubleStream; import static java.util.stream.IntStream.range;   public class Test implements DoubleSupplier {   private double mu, sigma; private double[] state = new double[2]; private int index = state.length;   Test(double m, double s) { mu = m; sigma = s; }   static double[] meanStdDev(double[] numbers) { if (numbers.length == 0) return new double[]{0.0, 0.0};   double sx = 0.0, sxx = 0.0; long n = 0; for (double x : numbers) { sx += x; sxx += pow(x, 2); n++; }   return new double[]{sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n}; }   static String replicate(int n, String s) { return range(0, n + 1).mapToObj(i -> s).collect(joining()); }   static void showHistogram01(double[] numbers) { final int maxWidth = 50; long[] bins = new long[10];   for (double x : numbers) bins[(int) (x * bins.length)]++;   double maxFreq = stream(bins).max().getAsLong();   for (int i = 0; i < bins.length; i++) System.out.printf(" %3.1f: %s%n", i / (double) bins.length, replicate((int) (bins[i] / maxFreq * maxWidth), "*")); System.out.println(); }   @Override public double getAsDouble() { index++; if (index >= state.length) { double r = sqrt(-2 * log(random())) * sigma; double x = 2 * PI * random(); state = new double[]{mu + r * sin(x), mu + r * cos(x)}; index = 0; } return state[index];   }   public static void main(String[] args) { Locale.setDefault(Locale.US); double[] data = DoubleStream.generate(new Test(0.0, 0.5)).limit(100_000) .toArray();   double[] res = meanStdDev(data); System.out.printf("Mean: %8.6f, SD: %8.6f%n", res[0], res[1]);   showHistogram01(stream(data).map(a -> max(0.0, min(0.9999, a / 3 + 0.5))) .toArray()); } }
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#Clojure
Clojure
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116])   (defn calc-stem [number] (int (Math/floor (/ number 10))))   (defn calc-leaf [number] (mod number 10))   (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors.   (new-plant 2) ;=> {0 [] 1 [] 2 []}" [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map))))   (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf))   (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves))))))   (stem-and-leaf data)  
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#BCPL
BCPL
get "libhdr"   manifest $( AMOUNT = 1200 $)   let gcd(a,b) = a>b -> gcd(a-b, b), a<b -> gcd(a, b-a), a   let mkstern(s, n) be $( s!1 := 1 s!2 := 1 for i=2 to n/2 do $( s!(i*2-1) := s!i + s!(i-1) s!(i*2) := s!i $) $)   let find(v, n, max) = valof for i=1 to max if v!i=n then resultis i   let findwrite(v, n, max) be writef("%I3 at %I4*N", n, find(v, n, max))   let start() be $( let stern = vec AMOUNT mkstern(stern, AMOUNT)   writes("First 15 numbers: ") for i=1 to 15 do writef("%N ", stern!i)   writes("*N*NFirst occurrence:*N") for i=1 to 10 do findwrite(stern, i, AMOUNT) findwrite(stern, 100, AMOUNT)   if valof $( for i=2 to AMOUNT unless gcd(stern!i, stern!(i-1)) = 1 resultis false resultis true $) then writes("*NThe GCD of each pair of consecutive members is 1.*N") $)
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Sidef
Sidef
func merge_streams(streams) { var s = streams.map { |stream| Pair(stream, stream.readline) }.grep {|p| defined(p.value) }   gather { while (s) { var p = s.min_by { .value } take(p.value) p.value = (p.key.readline \\ s.delete_if { _ == p }) } } }   say merge_streams(ARGV.map {|f| File(f).open_r }).join("\n")
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination. The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Traceback; with GNAT.Traceback.Symbolic;   procedure Test_Stack_Trace is procedure Call_Stack is Trace  : GNAT.Traceback.Tracebacks_Array (1..1_000); Length : Natural; begin GNAT.Traceback.Call_Chain (Trace, Length); Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (Trace (1..Length))); end Call_Stack;   procedure Inner (K : Integer) is begin Call_Stack; end Inner;   procedure Middle (X, Y : Integer) is begin Inner (X * Y); end Middle;   procedure Outer (A, B, C : Integer) is begin Middle (A + B, B + C); end Outer;   begin Outer (2,3,5); end Test_Stack_Trace;
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: Base case (if the step() call returns true): it stepped up one step. QED Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
#11l
11l
F step_up1() V deficit = 1 L deficit > 0 I step() deficit-- E deficit++
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" 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
#D
D
import std.stdio, std.algorithm, std.string, std.exception;   auto states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", // Uncomment the next line for the fake states. // "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" ];   void main() { states.length -= states.sort().uniq.copy(states).length;   string[][const ubyte[]] smap; foreach (immutable i, s1; states[0 .. $ - 1]) foreach (s2; states[i + 1 .. $]) smap[(s1 ~ s2).dup.representation.sort().release.assumeUnique] ~= s1 ~ " + " ~ s2;   writefln("%-(%-(%s = %)\n%)", smap.values.sort().filter!q{ a.length > 1 }); }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#J
J
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type :help for help, :quit for quit >>> println("Look no main!") Look no main! >>> :quit
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Julia
Julia
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type :help for help, :quit for quit >>> println("Look no main!") Look no main! >>> :quit
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Kotlin
Kotlin
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type :help for help, :quit for quit >>> println("Look no main!") Look no main! >>> :quit
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Logtalk
Logtalk
  :- initialization(main).  
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
proc main() = echo "Hello World!" main()
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Nim
Nim
proc main() = echo "Hello World!" main()
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Oforth
Oforth
: main(n) "Sleeping..." println n sleep "Awake and leaving." println ;
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#REXX
REXX
/*REXX program uses the straddling checkerboard cipher to encrypt/decrypt a message. */ parse arg msg /*obtain optional message from the C.L.*/ if msg='' then msg= 'One night-it was the twentieth of March, 1888-I was returning' say 'plain text=' msg call genCipher 'et aon ris', 'bcdfghjklm', 'pq/uvwxyz.' /*build the cipher (board)*/ enc= encrypt(msg); say ' encrypted=' enc /*encrypt message and show encryption. */ dec= decrypt(enc); say ' decrypted=' dec /*decrypt " " " decryption. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genCipher: @.=; arg @..,two,three; z= -1; @.z= @.. /*build top row of cipher.*/ _= pos(' ', @.. ) - 1; @._= two /* " 2nd " " " */ _= pos(' ', @.., _+2) - 1; @._= three /* " 3rd " " " */ do j=0 for 9; @..= @.. || @.j /*construct a table for fast searching.*/ if @.j\=='' then @.r= @.r || j _= pos('/', @.j) /*is the escape character in this row? */ if _\==0 then @.dig= j || (_-1) /*define " " for numerals.*/ end /*j*/ @..= space(@.., 0); return /*purify the table of encryptable chars*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ encrypt: procedure expose @.; arg !,,$ /*$: output (encrypted text) so far.*/ do j=1 for length(!) /*process each of the plain─text chars.*/ x= substr(!, j, 1) /*obtain a message char to be encrypted*/ if datatype(x, 'W') then do; $= $ || @.dig || x; iterate; end /*numeral?*/ if pos(x, @..)==0 then iterate /*Not one of the allowable chars? Skip*/ do k=-1 for 10; y= pos(x, @.k) /*traipse thru rows, looking for match.*/ if y==0 then iterate /*Not in this row? Then keep looking.*/ z= k; if z==-1 then z= /*construct the index of the cypher row*/ $= $ || z || (y-1); leave /*add an encrypted character to output.*/ end /*k*/ end /*j*/; return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ decrypt: procedure expose @.; parse arg !,,$ /*$: output (decrypted text) so far.*/ do j=1 to length(!); rw= -1 /*process each of the encypted numbers.*/ x= substr(!,j,1) /*obtain a message char to be decrypted*/ if substr(!,j,2)[email protected] then do; j= j+2; $= $ || substr(!, j, 1); iterate; end if pos(x, @.r)\==0 then do; j= j+1; rw=x; x=substr(!, j, 1); end $= $ || substr(@.rw, x+1, 1) /*add a character to decrypted message.*/ end /*j*/; return $
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials. Depending on the application, Stirling numbers of the first kind may be "signed" or "unsigned". Signed Stirling numbers of the first kind arise when the polynomial expansion is expressed in terms of falling factorials; unsigned when expressed in terms of rising factorials. The only substantial difference is that, for signed Stirling numbers of the first kind, values of S1(n, k) are negative when n + k is odd. Stirling numbers of the first kind follow the simple identities: S1(0, 0) = 1 S1(n, 0) = 0 if n > 0 S1(n, k) = 0 if k > n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned or S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed Task Write a routine (function, procedure, whatever) to find Stirling numbers of the first kind. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, S1(n, k), up to S1(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen. If your language supports large integers, find and show here, on this page, the maximum value of S1(n, k) where n == 100. See also Wikipedia - Stirling numbers of the first kind OEIS:A008275 - Signed Stirling numbers of the first kind OEIS:A130534 - Unsigned Stirling numbers of the first kind Related Tasks Stirling numbers of the second kind Lah numbers
#zkl
zkl
fcn stirling1(n,k){ var seen=Dictionary(); // cache for recursion if(n==k==0) return(1); if(n==0 or k==0) return(0);   z1,z2 := "%d,%d".fmt(n-1,k-1), "%d,%d".fmt(n-1,k); if(Void==(s1 := seen.find(z1))){ s1 = seen[z1] = stirling1(n - 1, k - 1) } if(Void==(s2 := seen.find(z2))){ s2 = seen[z2] = stirling1(n - 1, k) } (n - 1)*s2 + s1; // n is first to cast to BigInt (if using BigInts) }
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Maple
Maple
a := "Hello"; b := cat(a, " World"); c := `||`(a, " World");
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* mutable strings are not supported *) s1 = "testing"; s1 = s1 <> " 123"; s1
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#min
min
(quote cons "" join) :str-append   "foo" "bar" str-append puts!
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#jq
jq
cat /dev/urandom | tr -cd '0-9' | fold -w 10 | jq -nRr -f normal-distribution.jq
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#Julia
Julia
using Printf, Distributions, Gadfly   data = rand(Normal(0, 1), 1000) @printf("N = %i\n", length(data)) @printf("μ = %2.2f\tσ = %2.2f\n", mean(data), std(data)) @printf("range = (%2.2f, %2.2f\n)", minimum(data), maximum(data)) h = plot(x=data, Geom.histogram) draw(PNG("norm_hist.png", 10cm, 10cm), h)
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#D
D
import std.stdio, std.algorithm;   void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146];   int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#C
C
#include <stdio.h>   typedef unsigned int uint;   /* the sequence, 0-th member is 0 */ uint f(uint n) { return n < 2 ? n : (n&1) ? f(n/2) + f(n/2 + 1) : f(n/2); }   uint gcd(uint a, uint b) { return a ? a < b ? gcd(b%a, a) : gcd(a%b, b) : b; }   void find(uint from, uint to) { do { uint n; for (n = 1; f(n) != from ; n++); printf("%3u at Stern #%u.\n", from, n); } while (++from <= to); }   int main(void) { uint n; for (n = 1; n < 16; n++) printf("%u ", f(n)); puts("are the first fifteen.");   find(1, 10); find(100, 0);   for (n = 1; n < 1000 && gcd(f(n), f(n+1)) == 1; n++); printf(n == 1000 ? "All GCDs are 1.\n" : "GCD of #%d and #%d is not 1", n, n+1);   return 0; }
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Tcl
Tcl
#!/usr/bin/env tclsh proc merge {args} { set peeks {} foreach chan $args { if {[gets $chan peek] > 0} { dict set peeks $chan $peek } } set peeks [lsort -stride 2 -index 1 $peeks] while {[dict size $peeks]} { set peeks [lassign $peeks chan peek] puts $peek if {[gets $chan peek] > 0} { dict set peeks $chan $peek set peeks [lsort -stride 2 -index 1 $peeks] } } }   merge {*}[lmap f $::argv {open $f r}]  
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination. The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program.
#AutoHotkey
AutoHotkey
f() return   f() { return g() }   g() { ListLines msgbox, lines recently executed x = local to g ListVars msgbox, variable bindings } #Persistent
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination. The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program.
#BASIC
BASIC
100 DEF PROC callstack 110 ON ERROR GOTO 1000 120 FOR i=1 TO 100 130 POP lnum 140 LIST lnum TO lnum 150 NEXT i 190 END PROC 1000 PRINT "End of stack" 1010 STOP
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination. The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program.
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h>   #include <execinfo.h>   #define MAX_BT 200   void print_stack_trace() { void *buffer[MAX_BT]; int n;   n = backtrace(buffer, MAX_BT); fprintf(stderr, "--- (depth %d) ---\n", n); backtrace_symbols_fd(buffer, n, STDERR_FILENO); }     void inner(int k) { print_stack_trace(); }   void middle(int x, int y) { inner(x*y); }   void outer(int a, int b, int c) { middle(a+b, b+c); }   int main() { outer(2,3,5); return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: Base case (if the step() call returns true): it stepped up one step. QED Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
#ActionScript
ActionScript
function stepUp() { var i:int = 0; while(i < 1) if(step())i++; else i--; }
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure. Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers? Here's a pseudo-code of a simple recursive solution without using variables: func step_up() { if not step() { step_up(); step_up(); } } Inductive proof that step_up() steps up one step, if it terminates: Base case (if the step() call returns true): it stepped up one step. QED Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED The second (tail) recursion above can be turned into an iteration, as follows: func step_up() { while not step() { step_up(); } }
#Ada
Ada
procedure Step_Up is begin while not Step loop Step_Up; end loop; end Step_Up;
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented. Task Write a program to solve the challenge using both the original list of states and the fictitious list. Caveats case and spacing aren't significant - just letters (harmonize case) don't expect the names to be in any order - such as being sorted don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once) Comma separated list of state names used in the original puzzle: "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming" Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate): "New Kory", "Wen Kory", "York New", "Kory New", "New Kory" Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Go
Go
package main   import ( "fmt" "unicode" )   var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"}   func main() { play(states) play(append(states, "New Kory", "Wen Kory", "York New", "Kory New", "New Kory")) }   func play(states []string) { fmt.Println(len(states), "states:") // get list of unique state names set := make(map[string]bool, len(states)) for _, s := range states { set[s] = true } // make parallel arrays for unique state names and letter histograms s := make([]string, len(set)) h := make([][26]byte, len(set)) var i int for us := range set { s[i] = us for _, c := range us { if u := uint(unicode.ToLower(c)) - 'a'; u < 26 { h[i][u]++ } } i++ } // use map to find matches. map key is sum of histograms of // two different states. map value is indexes of the two states. type pair struct { i1, i2 int } m := make(map[string][]pair) b := make([]byte, 26) // buffer for summing histograms for i1, h1 := range h { for i2 := i1 + 1; i2 < len(h); i2++ { // sum histograms for i := range b { b[i] = h1[i] + h[i2][i] } k := string(b) // make key from buffer. // now loop over any existing pairs with the same key, // printing any where both states of this pair are different // than the states of the existing pair for _, x := range m[k] { if i1 != x.i1 && i1 != x.i2 && i2 != x.i1 && i2 != x.i2 { fmt.Printf("%s, %s = %s, %s\n", s[i1], s[i2], s[x.i1], s[x.i2]) } } // store this pair in the map whether printed or not. m[k] = append(m[k], pair{i1, i2}) } } }
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#PARI.2FGP
PARI/GP
BEGIN {...} # as soon as parsed CHECK {...} # end of compile time INIT {...} # beginning of run time END {...} # end of run time
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Pascal
Pascal
BEGIN {...} # as soon as parsed CHECK {...} # end of compile time INIT {...} # beginning of run time END {...} # end of run time
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Perl
Perl
BEGIN {...} # as soon as parsed CHECK {...} # end of compile time INIT {...} # beginning of run time END {...} # end of run time
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#Phix
Phix
procedure main() ... end procedure main()
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar trickery to force a startup procedure to run. Task Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup. Languages that always run from main() can be omitted from this task.
#PicoLisp
PicoLisp
println("hello world"); line(0, 0, width, height);
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
#Ruby
Ruby
class StraddlingCheckerboard EncodableChars = "A-Z0-9." SortedChars = " ./" + [*"A".."Z"].join   def initialize(board = nil) if board.nil? # create a new random board rest = "BCDFGHJKLMPQUVWXYZ/.".chars.shuffle @board = [" ESTONIAR".chars.shuffle, rest[0..9], rest[10..19]] elsif board.chars.sort.join == SortedChars @board = board.chars.each_slice(10).to_a else raise ArgumentError, "invalid #{self.class}: #{board}" end # find the indices of the first row blanks @row_labels = @board[0].each_with_index.select {|v, i| v == " "}.map {|v,i| i}   @mapping = {} @board[0].each_with_index {|char, idx| @mapping[char] = idx.to_s unless char == " "} @board[1..2].each_with_index do |row, row_idx| row.each_with_index do |char, idx| @mapping[char] = "%d%d" % [@row_labels[row_idx], idx] end end end   def encode(message) msg = message.upcase.delete("^#{EncodableChars}") msg.chars.inject("") do |crypt, char| crypt << (char =~ /[0-9]/ ? @mapping["/"] + char : @mapping[char]) end end   def decode(code) msg = "" tokens = code.chars until tokens.empty? token = tokens.shift itoken = token.to_i unless @row_labels.include?(itoken) msg << @board[0][itoken] else token2 = tokens.shift if @mapping["/"] == token + token2 msg << tokens.shift else msg << @board[1+@row_labels.index(itoken)][token2.to_i] end end end msg end   def to_s @board.inject("") {|res, row| res << row.join} end   def inspect "#<%s board=%p, row_labels=%p, mapping=%p>" % [self.class, to_s, @row_labels, @mapping] end end
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#MontiLang
MontiLang
|Hello | |world!| swap + print
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Nanoquery
Nanoquery
s1 = "this is" s1 += " a test"   println s1
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice. Task Create a string variable equal to any text value. Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it. Show the contents of the variable after the append operation.
#Neko
Neko
/** <doc><p>String append in Neko</pre></doc> **/   var str = "Hello" str += ", world" $print(str, "\n")
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data. Mention any native language support for the generation of normally distributed random numbers. Reference You may refer to code in Statistics/Basic if available.
#Kotlin
Kotlin
// version 1.1.2   val rand = java.util.Random()   fun normalStats(sampleSize: Int) { if (sampleSize < 1) return val r = DoubleArray(sampleSize) val h = IntArray(12) // all zero by default /* Generate 'sampleSize' normally distributed random numbers with mean 0.5 and SD 0.25 and calculate in which box they will fall when drawing the histogram */ for (i in 0 until sampleSize) { r[i] = 0.5 + rand.nextGaussian() / 4.0 when { r[i] < 0.0 -> h[0]++ r[i] >= 1.0 -> h[11]++ else -> h[1 + (r[i] * 10).toInt()]++ } }   // adjust one of the h[] values if necessary to ensure they sum to sampleSize val adj = sampleSize - h.sum() if (adj != 0) { for (i in 0..11) { h[i] += adj if (h[i] >= 0) break h[i] -= adj } }   val mean = r.average() val sd = Math.sqrt(r.map { (it - mean) * (it - mean) }.average())   // Draw a histogram of the data with interval 0.1 var numStars: Int // If sample size > 300 then normalize histogram to 300 val scale = if (sampleSize <= 300) 1.0 else 300.0 / sampleSize println("Sample size $sampleSize\n") println(" Mean ${"%1.6f".format(mean)} SD ${"%1.6f".format(sd)}\n") for (i in 0..11) { when (i) { 0 -> print("< 0.00 : ") 11 -> print(">=1.00 : ") else -> print("  %1.2f : ".format(i / 10.0)) } print("%5d ".format(h[i])) numStars = (h[i] * scale + 0.5).toInt() println("*".repeat(numStars)) } println() }   fun main(args: Array<String>) { val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000) for (sampleSize in sampleSizes) normalStats(sampleSize) }
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged. If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file. Note: If you wish to try multiple data sets, you might try this generator.
#Elixir
Elixir
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end   defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~#{stem_width}w | ~s~n" Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end)  :io.format fmt, [stem, leaves] end) end end   data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:     1, 1, 2 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1 Consider the next member of the series, (the third member i.e. 2) GOTO 3         ─── Expanding another loop we get: ─── Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:     1, 1, 2, 1, 3 Append the considered member of the sequence to the end of the sequence:     1, 1, 2, 1, 3, 2 Consider the next member of the series, (the fourth member i.e. 1) The task is to Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above. Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4) Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence. Show the (1-based) index of where the number 100 first appears in the sequence. Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one. Show your output on this page. Related tasks   Fusc sequence.   Continued fraction/Arithmetic Ref Infinite Fractions - Numberphile (Video). Trees, Teeth, and Time: The mathematics of clock making. A002487 The On-Line Encyclopedia of Integer Sequences.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   static class Program { static List<int> l = new List<int>() { 1, 1 };   static int gcd(int a, int b) { return a > 0 ? a < b ? gcd(b % a, a) : gcd(a % b, b) : b; }   static void Main(string[] args) { int max = 1000; int take = 15; int i = 1; int[] selection = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100 }; do { l.AddRange(new List<int>() { l[i] + l[i - 1], l[i] }); i += 1; } while (l.Count < max || l[l.Count - 2] != selection.Last()); Console.Write("The first {0} items In the Stern-Brocot sequence: ", take); Console.WriteLine("{0}\n", string.Join(", ", l.Take(take))); Console.WriteLine("The locations of where the selected numbers (1-to-10, & 100) first appear:"); foreach (int ii in selection) { int j = l.FindIndex(x => x == ii) + 1; Console.WriteLine("{0,3}: {1:n0}", ii, j); } Console.WriteLine(); bool good = true; for (i = 1; i <= max; i++) { if (gcd(l[i], l[i - 1]) != 1) { good = false; break; } } Console.WriteLine("The greatest common divisor of all the two consecutive items of the" + " series up to the {0}th item is {1}always one.", max, good ? "" : "not "); } }
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#UNIX_Shell
UNIX Shell
sort --merge source1 source2 sourceN > sink
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-stream merge The same as above, but reading from   N   sources. Common algorithm: same as above, but keep buffered items and their source descriptors in a heap. Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
#Wren
Wren
import "io" for File import "/ioutil" for FileUtil import "/str" for Str import "/seq" for Lst   var merge2 = Fn.new { |inputFile1, inputFile2, outputFile| // Note that the FileUtil.readEachLine method checks the file exists and closes it // when there are no more lines to read. var reader1 = Fiber.new(FileUtil.readEachLine(inputFile1)) var reader2 = Fiber.new(FileUtil.readEachLine(inputFile2)) var writer = File.create(outputFile) var line1 = reader1.call() var line2 = reader2.call() while (line1 && line2) { if (Str.le(line1, line2)) { writer.writeBytes(line1 + "\n") line1 = reader1.call() } else { writer.writeBytes(line2 + "\n") line2 = reader2.call() } } while (line1) { writer.writeBytes(line1 + "\n") line1 = reader1.call() } while (line2) { writer.writeBytes(line2 + "\n") line2 = reader2.call() } writer.close() }   var mergeN = Fn.new { |inputFiles, outputFile| var readers = inputFiles.map { |f| Fiber.new(FileUtil.readEachLine(f)) }.toList var writer = File.create(outputFile) var lines = readers.map { |reader| reader.call() }.toList while (lines.any { |line| line }) { var line = lines.where { |line| line }.reduce() { |acc, s| Str.lt(s, acc) ? s : acc } var index = Lst.indexOf(lines, line) writer.writeBytes(line + "\n") lines[index] = readers[index].call() } writer.close() }   var files = ["merge1.txt", "merge2.txt", "merge3.txt", "merge4.txt"] merge2.call(files[0], files[1], "merged2.txt") mergeN.call(files, "mergedN.txt") // check it worked System.print(File.read("merged2.txt")) System.print(File.read("mergedN.txt"))