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/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 # for n, k > 0 S2(n, n) = 1 S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1) Task Write a routine (function, procedure, whatever) to find Stirling numbers of the second kind. There are several methods to generate Stirling numbers of the second 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 second kind, S2(n, k), up to S2(12, 12). it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n). If your language supports large integers, find and show here, on this page, the maximum value of S2(n, k) where n == 100. See also Wikipedia - Stirling numbers of the second kind OEIS:A008277 - Stirling numbers of the second kind Related Tasks Stirling numbers of the first kind Bell numbers Lah numbers
#zkl
zkl
fcn stirling2(n,k){ var seen=Dictionary(); // cache for recursion if(n==k) return(1); // (0.0)==1 if(n<1 or k<1) return(0); z1,z2 := "%d,%d".fmt(n-1,k), "%d,%d".fmt(n-1,k-1); if(Void==(s1 := seen.find(z1))){ s1 = seen[z1] = stirling2(n-1,k) } if(Void==(s2 := seen.find(z2))){ s2 = seen[z2] = stirling2(n-1,k-1) } k*s1 + s2; // k is first to cast to BigInt (if using BigInts) }
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.
#Go
Go
package main   import ( "fmt" "strings" )   func main() { key := ` 8752390146 ET AON RIS 5BC/FGHJKLM 0PQD.VWXYZU` p := "you have put on 7.5 pounds since I saw you." fmt.Println(p) c := enc(key, p) fmt.Println(c) fmt.Println(dec(key, c)) }   func enc(bd, pt string) (ct string) { enc := make(map[byte]string) row := strings.Split(bd, "\n")[1:] r2d := row[2][:1] r3d := row[3][:1] for col := 1; col <= 10; col++ { d := string(row[0][col]) enc[row[1][col]] = d enc[row[2][col]] = r2d+d enc[row[3][col]] = r3d+d } num := enc['/'] delete(enc, '/') delete(enc, ' ') for i := 0; i < len(pt); i++ { if c := pt[i]; c <= '9' && c >= '0' { ct += num + string(c) } else { if c <= 'z' && c >= 'a' { c -= 'a'-'A' } ct += enc[c] } } return }   func dec(bd, ct string) (pt string) { row := strings.Split(bd, "\n")[1:] var cx [10]int for i := 1; i <= 10; i++ { cx[row[0][i]-'0'] = i } r2d := row[2][0]-'0' r3d := row[3][0]-'0' for i := 0; i < len(ct); i++ { var r int switch d := ct[i]-'0'; d { case r2d: r = 2 case r3d: r = 3 default: pt += string(row[1][cx[d]]) continue } i++ if b := row[r][cx[ct[i]-'0']]; b == '/' { i++ pt += string(ct[i]) } else { pt += string(b) } } 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
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } } s1[0][0].SetInt64(int64(1)) var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(n - 1)) t.Mul(&t, s1[n-1][k]) if unsigned { s1[n][k].Add(s1[n-1][k-1], &t) } else { s1[n][k].Sub(s1[n-1][k-1], &t) } } } fmt.Println("Unsigned Stirling numbers of the first kind: S1(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s1[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S1(100, *) row:") max := new(big.Int).Set(s1[limit][0]) for k := 1; k <= limit; k++ { if s1[limit][k].Cmp(max) > 0 { max.Set(s1[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
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.
#Dyalect
Dyalect
var str = "foo" str += str print(str)
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.
#EasyLang
EasyLang
a$ = "hello" a$ &= " world" print 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.
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq;   namespace RosettaCode { static class StreamMerge { static IEnumerable<T> Merge2<T>(IEnumerable<T> source1, IEnumerable<T> source2) where T : IComparable { var q1 = new Queue<T>(source1); var q2 = new Queue<T>(source2); while (q1.Any() && q2.Any()) { var c = q1.Peek().CompareTo(q2.Peek()); if (c <= 0) yield return q1.Dequeue(); else yield return q2.Dequeue(); } while (q1.Any()) yield return q1.Dequeue(); while (q2.Any()) yield return q2.Dequeue(); }   static IEnumerable<T> MergeN<T>(params IEnumerable<T>[] sources) where T : IComparable { var queues = sources.Select(e => new Queue<T>(e)).Where(q => q.Any()).ToList(); var headComparer = Comparer<Queue<T>>.Create((x, y) => x.Peek().CompareTo(y.Peek())); queues.Sort(headComparer);   while (queues.Any()) { var q = queues.First(); queues.RemoveAt(0); yield return q.Dequeue(); if (q.Any()) { var index = queues.BinarySearch(q, headComparer); queues.Insert(index < 0 ? ~index : index, q); } } }   static void Main() { var a = new[] { 1, 4, 7, 10 }; var b = new[] { 2, 5, 8, 11 }; var c = new[] { 3, 6, 9, 12 };   foreach (var i in Merge2(a, b)) Console.Write($"{i} "); Console.WriteLine();   foreach (var i in MergeN(a, b, c)) Console.Write($"{i} "); Console.WriteLine(); } } }
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.
#Haskell
Haskell
import Data.Char import Data.Map   charToInt :: Char -> Int charToInt c = ord c - ord '0'   -- Given a string, decode a single character from the string. -- Return the decoded char and the remaining undecoded string. decodeChar :: String -> (Char,String) decodeChar ('7':'9':r:rs) = (r,rs) decodeChar ('7':r:rs) = ("PQUVWXYZ. " !! charToInt r, rs) decodeChar ('3':r:rs) = ("ABCDFGIJKN" !! charToInt r, rs) decodeChar (r:rs) = ("HOL MES RT" !! charToInt r, rs)   -- Decode an entire string. decode :: String -> String decode [] = [] decode st = let (c, s) = decodeChar st in c:decode s   -- Given a string, decode a single character from the string. -- Return the decoded char and the part of the encoded string -- used to encode that character. revEnc :: String -> (Char, String) revEnc enc = let (dec, rm) = decodeChar enc in (dec, take (length enc - length rm) enc)   ds :: String ds = ['0'..'9']   -- Decode all 1000 possible encodings of three digits and -- use results to construct map used to encode. encodeMap :: Map Char String encodeMap = fromList [ revEnc [d2,d1,d0] | d2 <- ds, d1 <- ds, d0 <- ds ]   -- Encode a single char using encoding map. encodeChar :: Char -> String encodeChar c = findWithDefault "" c encodeMap   -- Encode an entire string. encode :: String -> String encode st = concatMap encodeChar $ fmap toUpper st   -- Test by encoding, decoding, printing results. main = let orig = "One night-it was on the twentieth of March, 1888-I was returning" enc = encode orig dec = decode enc in mapM_ putStrLn [ "Original: " ++ orig , "Encoded: " ++ enc , "Decoded: " ++ dec ]
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
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } } s1[0][0].SetInt64(int64(1)) var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(n - 1)) t.Mul(&t, s1[n-1][k]) if unsigned { s1[n][k].Add(s1[n-1][k-1], &t) } else { s1[n][k].Sub(s1[n-1][k-1], &t) } } } fmt.Println("Unsigned Stirling numbers of the first kind: S1(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s1[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S1(100, *) row:") max := new(big.Int).Set(s1[limit][0]) for k := 1; k <= limit; k++ { if s1[limit][k].Cmp(max) > 0 { max.Set(s1[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
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.
#EchoLisp
EchoLisp
  ;; Solution from Common Lisp and Racket (define-syntax-rule (set-append! str tail) (set! str (string-append str tail)))   (define name "Albert") → name   (set-append! name " de Jeumont-Schneidre") 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.
#Elena
Elena
import extensions; import extensions'text;   public program() { var s := StringWriter.load("Hello"); s.append:" World";   console.printLine:s.readChar() }
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.
#C.2B.2B
C++
//#include <functional> #include <iostream> #include <vector>   template <typename C, typename A> void merge2(const C& c1, const C& c2, const A& action) { auto i1 = std::cbegin(c1); auto i2 = std::cbegin(c2);   while (i1 != std::cend(c1) && i2 != std::cend(c2)) { if (*i1 <= *i2) { action(*i1); i1 = std::next(i1); } else { action(*i2); i2 = std::next(i2); } } while (i1 != std::cend(c1)) { action(*i1); i1 = std::next(i1); } while (i2 != std::cend(c2)) { action(*i2); i2 = std::next(i2); } }   template <typename A, typename C> void mergeN(const A& action, std::initializer_list<C> all) { using I = typename C::const_iterator; using R = std::pair<I, I>;   std::vector<R> vit; for (auto& c : all) { auto p = std::make_pair(std::cbegin(c), std::cend(c)); vit.push_back(p); }   bool done; R* least; do { done = true;   auto it = vit.begin(); auto end = vit.end(); least = nullptr;   // search for the first non-empty range to use for comparison while (it != end && it->first == it->second) { it++; } if (it != end) { least = &(*it); } while (it != end) { // search for the next non-empty range to use for comaprison while (it != end && it->first == it->second) { it++; } if (least != nullptr && it != end && it->first != it->second && *(it->first) < *(least->first)) { // found a smaller value least = &(*it); } if (it != end) { it++; } } if (least != nullptr && least->first != least->second) { done = false; action(*(least->first)); least->first = std::next(least->first); } } while (!done); }   void display(int num) { std::cout << num << ' '; }   int main() { std::vector<int> v1{ 0, 3, 6 }; std::vector<int> v2{ 1, 4, 7 }; std::vector<int> v3{ 2, 5, 8 };   merge2(v2, v1, display); std::cout << '\n';   mergeN(display, { v1 }); std::cout << '\n';   mergeN(display, { v3, v2, v1 }); std::cout << '\n'; }
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7)   text := "One night. it was on the twentieth of March, 1888. I was returning" write("text = ",image(text)) write("encode = ",image(en := StraddlingCheckerBoard("encode",text))) write("decode = ",image(StraddlingCheckerBoard("decode",en))) end   procedure StraddlingCheckerBoard(act,text,b1,b2) static SCE,SCD case act of { "setup" : { if (b1 < b2 < 10) & (*text = *cset(text) = 28) then { SCE := table("") SCD := table() esc := text[-1] # escape every text[(b1|b2)+1+:0] := " " # blanks uix := ["",b1,b2] # 1st position every c := text[1 + (i := 0 to *text-1)] do # build translation if c ~== " " then # skip blanks SCD[SCE[c] := SCE[map(c)] := uix[i/10+1]||(i%10) ] := c every c := !&digits do SCD[SCE[c] := SCE[esc] || c] := c delete(SCD,SCE[esc]) delete(SCE,esc) } else stop("Improper setup: ",image(text),", ",b1,", ",b2) } "encode" : { every (s := "") ||:= x := SCE[c := !text] return s } "decode" : { s := "" text ? until pos(0) do s ||:= \SCD[k := move(1 to 3)] return s } } end
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
#Haskell
Haskell
import Text.Printf (printf) import Data.List (groupBy) import qualified Data.MemoCombinators as Memo   stirling1 :: Integral a => (a, a) -> a stirling1 = Memo.pair Memo.integral Memo.integral f where f (n, k) | n == 0 && k == 0 = 1 | n > 0 && k == 0 = 0 | k > n = 0 | otherwise = stirling1 (pred n, pred k) + pred n * stirling1 (pred n, k)   main :: IO () main = do printf "n/k" mapM_ (printf "%10d") ([0..12] :: [Int]) >> printf "\n" printf "%s\n" $ replicate (13 * 10 + 3) '-' mapM_ (\row -> printf "%2d|" (fst $ head row) >> mapM_ (printf "%10d" . stirling1) row >> printf "\n") table printf "\nThe maximum value of S1(100, k):\n%d\n" $ maximum ([stirling1 (100, n) | n <- [1..100]] :: [Integer]) where table :: [[(Int, Int)]] table = groupBy (\a b -> fst a == fst b) $ (,) <$> [0..12] <*> [0..12]
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.
#Elixir
Elixir
iex(60)> s = "Hello" "Hello" iex(61)> s <> " World!" "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.
#Emacs_Lisp
Emacs Lisp
(defvar str "foo") (setq str (concat str "bar")) str ;=> "foobar"
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.
#11l
11l
F stern_brocot(predicate = series -> series.len < 20) V sb = [1, 1] V i = 0 L predicate(sb) sb [+]= [sum(sb[i .< i + 2]), sb[i + 1]] i++ R sb   V n_first = 15 print(("The first #. values:\n ".format(n_first))‘ ’stern_brocot(series -> series.len < :n_first)[0 .< n_first]) print()   V n_max = 10 L(n_occur) Array(1 .. n_max) [+] [100] print((‘1-based index of the first occurrence of #3 in the series:’.format(n_occur))‘ ’(stern_brocot(series -> @n_occur !C series).index(n_occur) + 1)) print()   V n_gcd = 1000 V s = stern_brocot(series -> series.len < :n_gcd)[0 .< n_gcd] assert(all(zip(s, s[1..]).map((prev, this) -> gcd(prev, this) == 1)), ‘A fraction from adjacent terms is reducible’)
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.
#D
D
import std.range.primitives; import std.stdio;   // An output range for writing the elements of the example ranges struct OutputWriter { void put(E)(E e) if (!isInputRange!E) { stdout.write(e); } }   void main() { import std.range : only; merge2(OutputWriter(), only(1,3,5,7), only(2,4,6,8)); writeln("\n---------------"); mergeN(OutputWriter(), only(1,4,7), only(2,5,8), only(3,6,9)); writeln("\n---------------"); mergeN(OutputWriter(), only(1,2,3)); }   /+ Write the smallest element from r1 and r2 until both ranges are empty +/ void merge2(IN,OUT)(OUT sink, IN r1, IN r2) if (isInputRange!IN && isOutputRange!(OUT, ElementType!IN)) { import std.algorithm : copy;   while (!r1.empty && !r2.empty) { auto a = r1.front; auto b = r2.front; if (a<b) { sink.put(a); r1.popFront; } else { sink.put(b); r2.popFront; } } copy(r1, sink); copy(r2, sink); }   /+ Write the smallest element from the sources until all ranges are empty +/ void mergeN(OUT,IN)(OUT sink, IN[] source ...) if (isInputRange!IN && isOutputRange!(OUT, ElementType!IN)) { ElementType!IN value; bool done, hasValue; int idx;   do { hasValue = false; done = true; idx = -1;   foreach(i,r; source) { if (!r.empty) { if (hasValue) { if (r.front < value) { value = r.front; idx = i; } } else { hasValue = true; value = r.front; idx = i; } } }   if (idx > -1) { sink.put(source[idx].front); source[idx].popFront; done = false; } } while (!done); }
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.
#J
J
'Esc Stop'=: '/.' 'Nums Alpha'=: '0123456789';'ABCDEFGHIJKLMNOPQRSTUVWXYZ' Charset=: Nums,Alpha,Stop   escapenum=: (,@:((; Esc&,)&>) Nums) rplc~ ] NB. escape numbers unescapenum=: ((, ; ' '&,@])"1 0 Nums"_) rplc~ ] NB. unescape coded numbers (x is escape code, y is cipher) expandKeyatUV=: 0:`[`(1 #~ 2 + #@])} #inv ] makeChkBrd=: Nums , expandKeyatUV   chkbrd=: conjunction define 'uv key'=. n board=. uv makeChkBrd key select. m case. 0 do. NB. encode digits=. board 10&#.inv@i. escapenum y ' ' -.~ ,(":@{:"1 digits) ,.~ (1 1 0 2{":uv) {~ {."1 digits case. 1 do. NB. decode esc=. 0 chkbrd (uv;key) Esc NB. find code for Esc char tmp=. esc unescapenum esc,'0',y tmp=. ((":uv) ((-.@e.~ _1&|.) *. e.~) tmp) <;.1 tmp NB. box on chars from rows 0 2 3 idx=. (}. ,~ (1 1 0 2{":uv) ":@i. {.) each tmp NB. recreate indices for rows 0 2 3 idx=. ;(2&{. , [: ((0 1 $~ +:@#) #inv!.'1' ]) 2&}.) each idx NB. recreate indices for row 1 }.board {~ _2 (_&".)\ idx end. )
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
#J
J
NB. agenda set by the test according to the definition test=: 1 i.~ (0 0&-: , 1 0&-:)@:*@:, , < s1=: 1:`0:`0:`($:&<: + (($: * [)~ <:)~)@.test s1&> table i. 13 +----+------------------------------------------------------------------------------------------+ |s1&>|0 1 2 3 4 5 6 7 8 9 10 11 12| +----+------------------------------------------------------------------------------------------+ | 0 |1 0 0 0 0 0 0 0 0 0 0 0 0| | 1 |0 1 0 0 0 0 0 0 0 0 0 0 0| | 2 |0 1 1 0 0 0 0 0 0 0 0 0 0| | 3 |0 2 3 1 0 0 0 0 0 0 0 0 0| | 4 |0 6 11 6 1 0 0 0 0 0 0 0 0| | 5 |0 24 50 35 10 1 0 0 0 0 0 0 0| | 6 |0 120 274 225 85 15 1 0 0 0 0 0 0| | 7 |0 720 1764 1624 735 175 21 1 0 0 0 0 0| | 8 |0 5040 13068 13132 6769 1960 322 28 1 0 0 0 0| | 9 |0 40320 109584 118124 67284 22449 4536 546 36 1 0 0 0| |10 |0 362880 1026576 1172700 723680 269325 63273 9450 870 45 1 0 0| |11 |0 3628800 10628640 12753576 8409500 3416930 902055 157773 18150 1320 55 1 0| |12 |0 39916800 120543840 150917976 105258076 45995730 13339535 2637558 357423 32670 1925 66 1| +----+------------------------------------------------------------------------------------------+ timespacex 's1&> table i. 13' 0.0242955 12928 NB. memoization greatly helps execution time s1M=: 1:`0:`0:`($:&<: + (($: * [)~ <:)~)@.test M. timespacex 's1M&> table i. 13' 0.000235206 30336 NB. third task >./100 s1M&x:&> i.101 19710908747055261109287881673376044669240511161402863823515728791076863288440277983854056472903481625299174865860036734731122707870406148096000000000000000000
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
#Java
Java
  import java.math.BigInteger; import java.util.HashMap; import java.util.Map;   public class SterlingNumbersFirstKind {   public static void main(String[] args) { System.out.println("Unsigned Stirling numbers of the first kind:"); int max = 12; System.out.printf("n/k"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%10d", n); } System.out.printf("%n"); for ( int n = 0 ; n <= max ; n++ ) { System.out.printf("%-3d", n); for ( int k = 0 ; k <= n ; k++ ) { System.out.printf("%10s", sterling1(n, k)); } System.out.printf("%n"); } System.out.println("The maximum value of S1(100, k) = "); BigInteger previous = BigInteger.ZERO; for ( int k = 1 ; k <= 100 ; k++ ) { BigInteger current = sterling1(100, k); if ( current.compareTo(previous) > 0 ) { previous = current; } else { System.out.printf("%s%n(%d digits, k = %d)%n", previous, previous.toString().length(), k-1); break; } } }   private static Map<String,BigInteger> COMPUTED = new HashMap<>();   private static final BigInteger sterling1(int n, int k) { String key = n + "," + k; if ( COMPUTED.containsKey(key) ) { return COMPUTED.get(key); } if ( n == 0 && k == 0 ) { return BigInteger.valueOf(1); } if ( n > 0 && k == 0 ) { return BigInteger.ZERO; } if ( k > n ) { return BigInteger.ZERO; } BigInteger result = sterling1(n-1, k-1).add(BigInteger.valueOf(n-1).multiply(sterling1(n-1, k))); COMPUTED.put(key, result); return result; }   }  
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.
#Erlang
Erlang
1> S = "Hello". "Hello" 2> S ++ " world". "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.
#Euphoria
Euphoria
  sequence string = "String"   printf(1,"%s\n",{string})   string &= " is now longer\n"   printf(1,"%s",{string})  
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.
#360_Assembly
360 Assembly
* Stern-Brocot sequence - 12/03/2019 STERNBR CSECT USING STERNBR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R4,SB+2 k=2; @sb(k) LA R2,SB+2 i=1; @sb(k-i) LA R3,SB+0 j=2; @sb(k-j) LA R1,NN/2 loop counter LOOP LA R4,2(R4) @sb(k)++ LH R0,0(R2) sb(k-i) AH R0,0(R3) sb(k-i)+sb(k-j) STH R0,0(R4) sb(k)=sb(k-i)+sb(k-j) LA R3,2(R3) @sb(k-j)++ LA R4,2(R4) @sb(k)++ LH R0,0(R3) sb(k-j) STH R0,0(R4) sb(k)=sb(k-j) LA R2,2(R2) @sb(k-i)++ BCT R1,LOOP end loop LA R9,15 n=15 MVC PG(5),=CL80'FIRST' XDECO R9,XDEC edit n MVC PG+5(3),XDEC+9 output n XPRNT PG,L'PG print buffer LA R10,PG @pg LA R6,1 i=1 DO WHILE=(CR,R6,LE,R9) do i=1 to n LR R1,R6 i SLA R1,1 ~ LH R2,SB-2(R1) sb(i) XDECO R2,XDEC edit sb(i) MVC 0(4,R10),XDEC+8 output sb(i) LA R10,4(R10) @pg+=4 LA R6,1(R6) i++ ENDDO , enddo i XPRNT PG,L'PG print buffer LA R7,1 j=1 DO WHILE=(C,R7,LE,=A(11)) do j=1 to 11 IF C,R7,EQ,=F'11' THEN if j=11 then LA R7,100 j=100 ENDIF , endif LA R6,1 i=1 DO WHILE=(C,R6,LE,=A(NN)) do i=1 to nn LR R1,R6 i SLA R1,1 ~ LH R2,SB-2(R1) sb(i) CR R2,R7 if sb(i)=j BE EXITI then leave i LA R6,1(R6) i++ ENDDO , enddo i EXITI MVC PG,=CL80'FIRST INSTANCE OF' XDECO R7,XDEC edit j MVC PG+17(4),XDEC+8 output j MVC PG+21(7),=C' IS AT ' XDECO R6,XDEC edit i MVC PG+28(4),XDEC+8 output i XPRNT PG,L'PG print buffer LA R7,1(R7) j++ ENDDO , enddo j L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav LTORG NN EQU 2400 nn PG DC CL80' ' buffer XDEC DS CL12 temp for xdeco SB DC (NN)H'1' sb(nn) REGEQU END STERNBR
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.
#Elixir
Elixir
defmodule StreamMerge do def merge2(file1, file2), do: mergeN([file1, file2])   def mergeN(files) do Enum.map(files, fn fname -> File.open!(fname) end) |> Enum.map(fn fd -> {fd, IO.read(fd, :line)} end) |> merge_loop end   defp merge_loop([]), do: :ok defp merge_loop(fdata) do {fd, min} = Enum.min_by(fdata, fn {_,head} -> head end) IO.write min case IO.read(fd, :line) do  :eof -> File.close(fd) List.delete(fdata, {fd, min}) |> merge_loop head -> List.keyreplace(fdata, fd, 0, {fd, head}) |> merge_loop end end end   filenames = ~w[temp1.dat temp2.dat temp3.dat] Enum.each(filenames, fn fname -> IO.puts "#{fname}: " <> File.read!(fname) |> String.replace("\n", " ") end) IO.puts "\n2-stream merge:" StreamMerge.merge2("temp1.dat", "temp2.dat") IO.puts "\nN-stream merge:" StreamMerge.mergeN(filenames)
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.
#Fortran
Fortran
SUBROUTINE FILEMERGE(N,INF,OUTF) !Merge multiple inputs into one output. INTEGER N !The number of input files. INTEGER INF(*) !Their unit numbers. INTEGER OUTF !The output file. INTEGER L(N) !The length of each current record. INTEGER LIST(0:N)!In sorted order. LOGICAL LIVE(N) !Until end-of-file. INTEGER ENUFF !As ever, how long is a piece of string? PARAMETER (ENUFF = 666) !Perhaps this will suffice. CHARACTER*(ENUFF) AREC(N)!One for each input file. INTEGER I,IT !Assistants. LIST = 0 !LIST(0) fingers the leader. LIVE = .TRUE. !All files are presumed live. Charge the battery. DO I = 1,N !Taste each. CALL GRAB(I) !By obtaining the first record. END DO !Also, preparing the LIST. Chug away. DO WHILE(LIST(0).GT.0) !Have we a leader? IT = LIST(0) !Yes. Which is it? WRITE (OUTF,"(A)") AREC(IT)(1:L(IT)) !Send it forth. LIST(0) = LIST(IT) !Head to the leader's follower. CALL GRAB(IT) !Get the next candidate. END DO !Try again.   CONTAINS !An assistant, called in two places. SUBROUTINE GRAB(IN) !Get another record. INTEGER IN !From this input file. INTEGER IT,P !Linked-list stepping. IF (.NOT.LIVE(IN)) RETURN !No more grist? READ (INF(IN),1,END = 10) L(IN),AREC(IN)(1:MIN(ENUFF,L(IN))) !Burp. 1 FORMAT (Q,A) !Q = "length remaining", obviously. Consider the place of AREC(IN) in the LIST. Entry LIST(IN) is to be linked back in. P = 0 !Finger the head of the LIST. 2 IT = LIST(P) !Which supplier is fingered? IF (IT.GT.0) THEN !If we're not at the end, IF (AREC(IN)(1:L(IN)).GT.AREC(IT)(1:L(IT))) THEN !Compare. P = IT !The incomer follows this node. GO TO 2 !So, move to IT and check afresh. END IF !So much for the comparison. END IF !The record from supplier IN is to precede that from IT, fingered by LIST(P). LIST(IN) = IT !So, IN's follower is IT. LIST(P) = IN !And P's follower is now IN. RETURN !Done. 10 LIVE(IN) = .FALSE. !No further input. LIST(IN) = -666 !This will cause trouble if accessed. END SUBROUTINE GRAB !Grab input, and jostle for position. END SUBROUTINE FILEMERGE !Simple...   PROGRAM MASH INTEGER MANY PARAMETER (MANY = 4) !Sufficient? INTEGER FI(MANY) CHARACTER*(28) FNAME(MANY) DATA FNAME/"FileAppend.for","FileChop.for", 1 "FileExt.for","FileHack.for"/ INTEGER I,F   F = 10 !Safely past pre-defined unit numbers. OPEN (F,FILE="Merged.txt",STATUS="REPLACE",ACTION="WRITE") !File for output. DO I = 1,MANY !Go for the input files. FI(I) = F + I !Choose another unit number. OPEN (FI(I),FILE=FNAME(I),STATUS="OLD",ACTION="READ") !Hope. END DO !On to the next.   CALL FILEMERGE(MANY,FI,F) !E pluribus unum.   END !That was easy.
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.
#Java
Java
import java.util.HashMap; import java.util.Map; import java.util.regex.*;   public class StraddlingCheckerboard {   final static String[] keyvals = {"H:0", "O:1", "L:2", "M:4", "E:5", "S:6", "R:8", "T:9", "A:30", "B:31", "C:32", "D:33", "F:34", "G:35", "I:36", "J:37", "K:38", "N:39", "P:70", "Q:71", "U:72", "V:73", "W:74", "X:75", "Y:76", "Z:77", ".:78", "/:79", "0:790", "1:791", "2:792", "3:793", "4:794", "5:795", "6:796", "7:797", "8:798", "9:799"};   final static Map<String, String> val2key = new HashMap<>(); final static Map<String, String> key2val = new HashMap<>();   public static void main(String[] args) { for (String keyval : keyvals) { String[] kv = keyval.split(":"); val2key.put(kv[0], kv[1]); key2val.put(kv[1], kv[0]); } String enc = encode("One night-it was on the twentieth of March, " + "1888-I was returning"); System.out.println(enc); System.out.println(decode(enc)); }   static String encode(String s) { StringBuilder sb = new StringBuilder(); for (String c : s.toUpperCase().split("")) { c = val2key.get(c); if (c != null) sb.append(c); } return sb.toString(); }   static String decode(String s) { Matcher m = Pattern.compile("(79.|3.|7.|.)").matcher(s); StringBuilder sb = new StringBuilder(); while (m.find()) { String v = key2val.get(m.group(1)); if (v != null) sb.append(v); } return sb.toString(); } }
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
#jq
jq
# For efficiency, define the helper function for `stirling1/2` as a # top-level function so we can use it directly for constructing the table: # input: [m,j,cache] # output: [s, cache] def stirling1: . as [$m, $j, $cache] | "\($m),\($j)" as $key | $cache | if has($key) then [.[$key], .] elif $m == 0 and $j == 0 then [1, .] elif $m > 0 and $j == 0 then [0, .] elif $j > $m then [0, .] else ([$m-1, $j-1, .] | stirling1) as [$s1, $c1] | ([$m-1, $j, $c1] | stirling1) as [$s2, $c2] | (($s1 + ($m-1) * $s2)) as $result | ($c2 | (.[$key] = $result)) as $c3 | [$result, $c3] end;   def stirling1($n; $k): [$n, $k, {}] | stirling1 | .[0];   # produce the table for 0 ... $n inclusive def stirlings($n): # state: [cache, array_of_results] reduce range(0; $n+1) as $i ([{}, []]; reduce range(0; $i+1) as $j (.; . as [$cache, $a] | ([$i, $j, $cache] | stirling1) as [$s, $c] | [$c, ($a|setpath([$i,$j]; $s))] ));   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def task($n): "Unsigned Stirling numbers of the first kind:", "n/k \( [range(0;$n+1)|lpad(10)] | join(" "))", ((stirlings($n) | .[1]) as $a | range(0; $n+1) as $i | "\($i|lpad(3)): \( [$a[$i][]| lpad(10)] | join(" ") )" ), "\nThe maximum value of S1(100, k) is", ([stirling1(100; range(0;101)) ] | max) ;   task(12)
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
#Julia
Julia
using Combinatorics   const s1cache = Dict()   function stirlings1(n, k, signed::Bool=false) if signed == true && isodd(n - k) return -stirlings1(n, k) elseif haskey(s1cache, Pair(n, k)) return s1cache[Pair(n, k)] elseif n < 0 throw(DomainError(n, "n must be nonnegative")) elseif n == k == 0 return one(n) elseif n == 0 || k == 0 return zero(n) elseif n == k return one(n) elseif k == 1 return factorial(n-1) elseif k == n - 1 return binomial(n, 2) elseif k == n - 2 return div((3 * n - 1) * binomial(n, 3), 4) elseif k == n - 3 return binomial(n, 2) * binomial(n, 4) end   ret = (n - 1) * stirlings1(n - 1, k) + stirlings1(n - 1, k - 1) s1cache[Pair(n, k)] = ret return ret end   function printstirling1table(kmax) println(" ", mapreduce(i -> lpad(i, 10), *, 0:kmax))   sstring(n, k) = begin i = stirlings1(n, k); lpad(k > n && i == 0 ? "" : i, 10) end   for n in 0:kmax println(rpad(n, 2) * mapreduce(k -> sstring(n, k), *, 0:kmax)) end end   printstirling1table(12) println("\nThe maximum for stirling1(100, _) is:\n", maximum(k-> stirlings1(BigInt(100), BigInt(k)), 1:100))  
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.
#F.23
F#
let mutable x = "foo" x <- x + "bar" printfn "%s" 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.
#Factor
Factor
"Hello, " "world!" append
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.
#11l
11l
F leaf_plot(&x) x.sort() V i = x[0] I/ 10 - 1 L(j) 0 .< x.len V d = x[j] I/ 10 L d > i i++ print(‘#.#3 |’.format((j != 0) * "\n", i), end' ‘’) print(‘ ’(x[j] % 10), end' ‘’) print()   V 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 ]   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.
#8080_Assembly
8080 Assembly
puts: equ 9 ; CP/M syscall to print a string org 100h ;;; Generate the first 1200 elements of the Stern-Brocot sequence lxi b,600 ; 2 elements generated per loop lxi h,seq mov e,m ; Initialization inx h push h ; Save considered member pointer inx h ; Insertion pointer genseq: xthl ; Load considered member pointer mov d,e ; D = predecessor mov e,m ; E = considered member inx h ; Point at next considered member xthl ; Load insertion pointer mov a,d ; A = sum of both members add e mov m,a ; Append the sum inx h mov m,e ; Append the considered member inx h dcx b ; Decrement counter mov a,b ; Zero? ora c jnz genseq ; If not, generate next members of sequence pop h ; Remove pointer from stack ;;; Print first 15 members of sequence lxi d,seq mvi b,15 ; 15 members mvi h,0 p15: ldax d ; Get current member mov l,a call prhl ; Print member inx d ; Increment pointer dcr b ; Decrement counter jnz p15 ; If not zero, print another one lxi d,nl mvi c,puts call 5 ;;; Print indices of first occurrence of 1..10 lxi b,010Ah ; B = number, C = counter call fnext ;;; Print index of first occurrence of 100 lxi b,6401h call fnext ;;; Check if the GCD of first 1000 consecutive elements is 0 xra a ; Zero out 1001th element as end marker sta seq+1000 lxi h,seq ; Start of array mov e,m inx h gcdchk: mov d,e ; (D,E) = next pair mov e,m inx h mov a,e mov b,d ana a ; Reached the end? jz done call gcd ; If not, check GCD dcr a ; Check that it is 1 jz gcdchk ; If so, check next pair push h ; GCD not 1 - save pointer lxi d,gcdn ; Print message mvi c,puts call 5 pop h ; Calculate offset in array lxi d,-seq dad d jmp prhl ; Print offset of pair whose GCD is not 1 done: lxi d,gcdy ; Print OK message mvi c,puts jmp 5 ;;; GCD(A,B) gcd: cmp b rz ; If A=B, result = A jc b_le_a ; B>A? sub b ; If A>B, subtract B jmp gcd ; and loop b_le_a: mov c,a mov a,b sub c mov b,a mov a,c jmp gcd ;;; Print indices of occurrences of C numbers ;;; starting at B fnext: lxi d,seq fsrch: ldax d ; Get current member cmp b ; Is it the number we are looking for? inx d ; Increment number jnz fsrch ; If no match, check next number lxi h,-seq ; Match - subtract start of array dad d call prhl ; Print index inr b ; Look for next number dcr c ; If we need more numbers jnz fnext push d ; Save sequence pointer lxi d,nl ; Print newline mvi c,puts call 5 pop d ; Restore sequence pointer ret ;;; Print HL as ASCII number. prhl: push h ; Save all registers push d push b lxi b,pnum ; Store pointer to num string on stack push b lxi b,-10 ; Divisor prdgt: lxi d,-1 prdgtl: inx d ; Divide by 10 through trial subtraction dad b jc prdgtl mvi a,'0'+10 add l ; L = remainder - 10 pop h ; Get pointer from stack dcx h ; Store digit mov m,a push h ; Put pointer back on stack xchg ; Put quotient in HL mov a,h ; Check if zero ora l jnz prdgt ; If not, next digit pop d ; Get pointer and put in DE mvi c,9 ; CP/M print string call 5 pop b ; Restore registers pop d pop h ret db '*****' ; Placeholder for number pnum: db ' $' nl: db 13,10,'$' gcdn: db 'GCD not 1 at: $' gcdy: db 'GCD of all pairs of consecutive members is 1.$' seq: db 1,1 ; Sequence stored here
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.
#Go
Go
package main   import ( "container/heap" "fmt" "io" "log" "os" "strings" )   var s1 = "3 14 15" var s2 = "2 17 18" var s3 = "" var s4 = "2 3 5 7"   func main() { fmt.Print("merge2: ") merge2( os.Stdout, strings.NewReader(s1), strings.NewReader(s2)) fmt.Println()   fmt.Print("mergeN: ") mergeN( os.Stdout, strings.NewReader(s1), strings.NewReader(s2), strings.NewReader(s3), strings.NewReader(s4)) fmt.Println() }   func r1(r io.Reader) (v int, ok bool) { switch _, err := fmt.Fscan(r, &v); { case err == nil: return v, true case err != io.EOF: log.Fatal(err) } return }   func merge2(m io.Writer, s1, s2 io.Reader) { v1, d1 := r1(s1) v2, d2 := r1(s2) var v int for d1 || d2 { if !d2 || d1 && v1 < v2 { v = v1 v1, d1 = r1(s1) } else { v = v2 v2, d2 = r1(s2) } fmt.Fprint(m, v, " ") } }   type sv struct { s io.Reader v int }   type sh []sv   func (s sh) Len() int { return len(s) } func (s sh) Less(i, j int) bool { return s[i].v < s[j].v } func (s sh) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (p *sh) Push(x interface{}) { *p = append(*p, x.(sv)) } func (p *sh) Pop() interface{} { s := *p last := len(s) - 1 v := s[last] *p = s[:last] return v }   func mergeN(m io.Writer, s ...io.Reader) { var h sh for _, s := range s { if v, d := r1(s); d { h = append(h, sv{s, v}) } } heap.Init(&h) for len(h) > 0 { p := heap.Pop(&h).(sv) fmt.Fprint(m, p.v, " ") if v, d := r1(p.s); d { heap.Push(&h, sv{p.s, v}) } } }
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.
#JavaScript
JavaScript
<script> var alphabet=new Array("ESTONIA R","BCDFGHJKLM","PQUVWXYZ./") // scramble alphabet as you wish var prefixes=new Array("",alphabet[0].indexOf(" "),alphabet[0].lastIndexOf(" "))   function straddle(message){ var out="" message=message.toUpperCase() message=message.replace(/([0-9])/g,"/$1") // dumb way to escape numbers for(var i=0;i<message.length;i++){ var chr=message[i] if(chr==" ")continue for(var j=0;j<3;j++){ var k=alphabet[j].indexOf(chr) if(k<0)continue out+=prefixes[j].toString()+k } if(chr=="/")out+=message[++i] } return out }   function unstraddle(message){ var out="" var n,o for(var i=0;i<message.length;i++){ n=message[i]*1 switch(n){ case prefixes[1]: o=alphabet[1][message[++i]];break case prefixes[2]: o=alphabet[2][message[++i]];break default: o=alphabet[0][n] } o=="/"?out+=message[++i]:out+=o } return out }   str="One night-it was on the twentieth of March, 1888-I was returning." document.writeln(str) document.writeln(straddle(str)) document.writeln(unstraddle(straddle(str))) </script>
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
#Kotlin
Kotlin
import java.math.BigInteger   fun main() { println("Unsigned Stirling numbers of the first kind:") val max = 12 print("n/k") for (n in 0..max) { print("%10d".format(n)) } println() for (n in 0..max) { print("%-3d".format(n)) for (k in 0..n) { print("%10s".format(sterling1(n, k))) } println() } println("The maximum value of S1(100, k) = ") var previous = BigInteger.ZERO for (k in 1..100) { val current = sterling1(100, k) previous = if (current!! > previous) { current } else { println("$previous\n(${previous.toString().length} digits, k = ${k - 1})") break } } }   private val COMPUTED: MutableMap<String, BigInteger?> = HashMap() private fun sterling1(n: Int, k: Int): BigInteger? { val key = "$n,$k" if (COMPUTED.containsKey(key)) { return COMPUTED[key] }   if (n == 0 && k == 0) { return BigInteger.valueOf(1) } if (n > 0 && k == 0) { return BigInteger.ZERO } if (k > n) { return BigInteger.ZERO }   val result = sterling1(n - 1, k - 1)!!.add(BigInteger.valueOf(n - 1.toLong()).multiply(sterling1(n - 1, k))) COMPUTED[key] = result return result }
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.
#Falcon
Falcon
  /* Added by Aykayayciti Earl Lamont Montgomery April 10th, 2018 */   s1, s2 = "Hello", "Foo" > s1 + " World" printl(s2 + " bar")  
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.
#Forth
Forth
\ Strings in Forth are simply named memory locations   create astring 256 allot \ create a "string"   s" Hello " astring PLACE \ initialize the string   s" World!" astring +PLACE \ append with "+place"
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.
#ACL2
ACL2
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs))))   (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs)))))   (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs)))))))   (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin)))))   (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins)))))   (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
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.
#8086_Assembly
8086 Assembly
puts: equ 9 cpu 8086 bits 16 org 100h section .text ;;; Generate the first 1200 elemets of the Stern-Brocot sequence mov cx,600 ; 2 elements generated per loop mov si,seq mov di,seq+2 lodsb mov ah,al ; AH = predecessor genseq: lodsb ; AL = considered member add ah,al ; AH = sum xchg ah,al ; Swap them (AL = sum, AH = member) stosw ; Write sum and current considered member loop genseq ; Loop 600 times ;;; Print first 15 members of sequence mov si,seq mov cx,15 p15: lodsb ; Get member cbw call prax ; Print member loop p15 call prnl ;;; Print first occurrences of [1..10] mov al,1 mov cx,10 call find call prnl ;;; Print first occurrence of 100 mov al,100 mov cx,1 call find call prnl ;;; Check pairs of GCDs mov cx,1000 ; 1000 times mov si,seq lodsb gcdchk: mov ah,al ; AH = last member, AL = current member lodsb mov dx,ax ; Calculate GCD call gcd dec dl ; See if it is 1 jnz .fail ; If not, failure loop gcdchk ; Otherwise, check next pair mov dx,gcdy ; GCD of all pairs is 0 jmp pstr .fail: mov dx,gcdn ; GCD of current pair is not 0 call pstr mov ax,si sub ax,seq+1 jmp prax ;;; DL = gcd(DL,DH) gcd: cmp dl,dh jl .lt ; DL < DH jg .gt ; DL > DH ret .lt: sub dh,dl ; DL < DH jmp gcd .gt: sub dl,dh ; DL > DH jmp gcd ;;; Print indices of CX consecutive numbers starting ;;; at AL. find: mov di,seq push cx ; Keep loop counter mov cx,-1 repne scasb ; Find AL starting at [DI] pop cx ; Restore loop counter xchg si,ax ; Keep AL in SI mov ax,di ; Calculate index in sequence sub ax,seq call prax ; Output xchg si,ax ; Restore AL inc ax ; Increment loop find ; Keep going CX times ret ;;; Print newline prnl: mov dx,nl jmp pstr ;;; Print number in AX ;;; Destroys AX, BX, DX, BP prax: mov bp,10 ; Divisor mov bx,numbuf .loop: xor dx,dx ; DX = 0 div bp ; Divide DX:AX by 10; DX = remainder dec bx ; Move string pointer back add dl,'0' ; Make ASCII digit mov [bx],dl ; Write digit test ax,ax ; Any digits left? jnz .loop mov dx,bx pstr: mov ah,puts ; Print number string int 21h ret section .data gcdn: db 'GCD not 1 at: $' gcdy: db 'GCD of all pairs of consecutive members is 1.$' db '*****' numbuf: db ' $' nl: db 13,10,'$' seq: db 1,1
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.
#Haskell
Haskell
-- stack runhaskell --package=conduit-extra --package=conduit-merge   import Control.Monad.Trans.Resource (runResourceT) import qualified Data.ByteString.Char8 as BS import Data.Conduit (($$), (=$=)) import Data.Conduit.Binary (sinkHandle, sourceFile) import qualified Data.Conduit.Binary as Conduit import qualified Data.Conduit.List as Conduit import Data.Conduit.Merge (mergeSources) import System.Environment (getArgs) import System.IO (stdout)   main :: IO () main = do inputFileNames <- getArgs let inputs = [sourceFile file =$= Conduit.lines | file <- inputFileNames] runResourceT $ mergeSources inputs $$ sinkStdoutLn where sinkStdoutLn = Conduit.map (`BS.snoc` '\n') =$= sinkHandle stdout
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.
#Julia
Julia
  function straddlingcheckerboard(board, msg, doencode) lookup = Dict() reverselookup = Dict() row2 = row3 = slash = -1 function encode(x) s = "" for ch in replace(replace(uppercase(x), r"([01-9])", s";=;\1"), r";=;", slash) c = string(ch) if haskey(lookup, c) s *= lookup[c] elseif contains("0123456789", c) s *= c end end s end function decode(x) s = "" i = 1 while i <= length(x) c = string(x[i]) if haskey(reverselookup, c) s *= reverselookup[c] i += 1 else if "$c$(x[i+1])" == slash s *= string(x[i+2]) i += 3 else s *= reverselookup["$c$(x[i+1])"] i += 2 end end end s end for (i,c) in enumerate(board) c = string(c) if c == " " if row2 == -1 row2 = i-1 else row3 = i-1 end else if i < 11 lookup[c] = "$(i-1)"; reverselookup["$(i-1)"] = c elseif i < 21 lookup[c] = "$row2$(i-11)"; reverselookup["$row2$(i-11)"] = c else lookup[c] = "$row3$(i-21)"; reverselookup["$row3$(i-21)"] = c end if c == "/" slash = lookup[c] end end end doencode ? encode(msg) : decode(msg) end   btable = "ET AON RISBCDFGHJKLMPQ/UVWXYZ." message = "Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour." encoded = straddlingcheckerboard(btable, message, true) decoded = straddlingcheckerboard(btable, encoded, false) println("Original: $message\nEncoded: $encoded\nDecoded: $decoded")  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
TableForm[Array[StirlingS1, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}] Max[Abs[StirlingS1[100, #]] & /@ Range[0, 100]]
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
#Nim
Nim
import sequtils, strutils   proc s1(n, k: Natural): Natural = if k == 0: return ord(n == 0) if k > n: return 0 s1(n - 1, k - 1) + (n - 1) * s1(n - 1, k)   echo " k ", toSeq(0..12).mapIt(($it).align(2)).join(" ") echo " n" for n in 0..12: stdout.write ($n).align(2) for k in 0..n: stdout.write ($s1(n, k)).align(10) stdout.write '\n'
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.
#Fortran
Fortran
  program main   character(len=:),allocatable :: str   str = 'hello' str = str//' world'   write(*,*) str   end program 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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Var s = "String" s += " append" Print s Sleep
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.
#C
C
/* * RosettaCode example: Statistics/Normal distribution in C * * The random number generator rand() of the standard C library is obsolete * and should not be used in more demanding applications. There are plenty * libraries with advanced features (eg. GSL) with functions to calculate * the mean, the standard deviation, generating random numbers etc. * However, these features are not the core of the standard C library. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h>     #define NMAX 10000000     double mean(double* values, int n) { int i; double s = 0;   for ( i = 0; i < n; i++ ) s += values[i]; return s / n; }     double stddev(double* values, int n) { int i; double average = mean(values,n); double s = 0;   for ( i = 0; i < n; i++ ) s += (values[i] - average) * (values[i] - average); return sqrt(s / (n - 1)); }   /* * Normal random numbers generator - Marsaglia algorithm. */ double* generate(int n) { int i; int m = n + n % 2; double* values = (double*)calloc(m,sizeof(double)); double average, deviation;   if ( values ) { for ( i = 0; i < m; i += 2 ) { double x,y,rsq,f; do { x = 2.0 * rand() / (double)RAND_MAX - 1.0; y = 2.0 * rand() / (double)RAND_MAX - 1.0; rsq = x * x + y * y; }while( rsq >= 1. || rsq == 0. ); f = sqrt( -2.0 * log(rsq) / rsq ); values[i] = x * f; values[i+1] = y * f; } } return values; }     void printHistogram(double* values, int n) { const int width = 50; int max = 0;   const double low = -3.05; const double high = 3.05; const double delta = 0.1;   int i,j,k; int nbins = (int)((high - low) / delta); int* bins = (int*)calloc(nbins,sizeof(int)); if ( bins != NULL ) { for ( i = 0; i < n; i++ ) { int j = (int)( (values[i] - low) / delta ); if ( 0 <= j && j < nbins ) bins[j]++; }   for ( j = 0; j < nbins; j++ ) if ( max < bins[j] ) max = bins[j];   for ( j = 0; j < nbins; j++ ) { printf("(%5.2f, %5.2f) |", low + j * delta, low + (j + 1) * delta ); k = (int)( (double)width * (double)bins[j] / (double)max ); while(k-- > 0) putchar('*'); printf("  %-.1f%%", bins[j] * 100.0 / (double)n); putchar('\n'); }   free(bins); } }     int main(void) { double* seq;   srand((unsigned int)time(NULL));   if ( (seq = generate(NMAX)) != NULL ) { printf("mean = %g, stddev = %g\n\n", mean(seq,NMAX), stddev(seq,NMAX)); printHistogram(seq,NMAX); free(seq);   printf("\n%s\n", "press enter"); getchar(); return EXIT_SUCCESS; } return EXIT_FAILURE; }
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.
#Action.21
Action!
INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit   PROC Main() DEFINE len="121" BYTE ARRAY a(len)=[ 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] BYTE i,j,min,max,stem,leaf   Put(125) PutE() ;clear screen SortB(a,len,0) min=a(0)/10 max=a(len-1)/10 FOR i=min TO max DO IF i<10 THEN Put(' ) FI PrintB(i) Print("* | ") FOR j=0 TO len-1 DO stem=a(j)/10 IF stem=i THEN leaf=a(j) MOD 10 PrintB(leaf) FI OD PutE() OD RETURN
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.
#Action.21
Action!
PROC Generate(BYTE ARRAY seq INT POINTER count INT minCount,maxVal) INT i   seq(0)=1 seq(1)=1 count^=2 i=1 WHILE count^<minCount OR seq(count^-1)#maxVal AND seq(count^-2)#maxVal DO seq(count^)=seq(i-1)+seq(i) seq(count^+1)=seq(i) count^==+2 i==+1 OD RETURN   PROC PrintSeq(BYTE ARRAY seq INT count) INT i   PrintF("First %I items:%E",count) FOR i=0 TO count-1 DO PrintB(seq(i)) Put(32) OD PutE() PutE() RETURN   PROC PrintLoc(BYTE ARRAY seq INT seqCount BYTE ARRAY loc INT locCount) INT i,j BYTE value   FOR i=0 TO locCount-1 DO j=0 value=loc(i) WHILE seq(j)#value DO j==+1 OD PrintF("%B appears at position %I%E",value,j+1) OD PutE() RETURN   BYTE FUNC Gcd(BYTE a,b) BYTE tmp   IF a<b THEN tmp=a a=b b=tmp FI   WHILE b#0 DO tmp=a MOD b a=b b=tmp OD RETURN (a)   PROC PrintGcd(BYTE ARRAY seq INT count) INT i   FOR i=0 TO count-2 DO IF Gcd(seq(i),seq(i+1))>1 THEN PrintF("GCD between %I and %I item is greater than 1",i+1,i+2) RETURN FI OD Print("GCD between all two consecutive items of the sequence is equal 1") RETURN   PROC Main() BYTE ARRAY seq(2000),loc=[1 2 3 4 5 6 7 8 9 10 100] INT count   Generate(seq,@count,1000,100) PrintSeq(seq,15) PrintLoc(seq,count,loc,11) PrintGcd(seq,1000) RETURN
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.
#Java
Java
import java.util.Iterator; import java.util.List; import java.util.Objects;   public class StreamMerge { private static <T extends Comparable<T>> void merge2(Iterator<T> i1, Iterator<T> i2) { T a = null, b = null;   while (i1.hasNext() || i2.hasNext()) { if (null == a && i1.hasNext()) { a = i1.next(); } if (null == b && i2.hasNext()) { b = i2.next(); }   if (null != a) { if (null != b) { if (a.compareTo(b) < 0) { System.out.print(a); a = null; } else { System.out.print(b); b = null; } } else { System.out.print(a); a = null; } } else if (null != b) { System.out.print(b); b = null; } }   if (null != a) { System.out.print(a); } if (null != b) { System.out.print(b); } }   @SuppressWarnings("unchecked") @SafeVarargs private static <T extends Comparable<T>> void mergeN(Iterator<T>... iter) { Objects.requireNonNull(iter); if (iter.length == 0) { throw new IllegalArgumentException("Must have at least one iterator"); }   Object[] pa = new Object[iter.length]; boolean done;   do { done = true;   for (int i = 0; i < iter.length; i++) { Iterator<T> t = iter[i]; if (null == pa[i] && t.hasNext()) { pa[i] = t.next(); } }   T min = null; int idx = -1; for (int i = 0; i < pa.length; ++i) { T t = (T) pa[i]; if (null != t) { if (null == min) { min = t; idx = i; done = false; } else if (t.compareTo(min) < 0) { min = t; idx = i; done = false; } } } if (idx != -1) { System.out.print(min); pa[idx] = null; } } while (!done); }   public static void main(String[] args) { List<Integer> l1 = List.of(1, 4, 7, 10); List<Integer> l2 = List.of(2, 5, 8, 11); List<Integer> l3 = List.of(3, 6, 9, 12);   merge2(l1.iterator(), l2.iterator()); System.out.println();   mergeN(l1.iterator(), l2.iterator(), l3.iterator()); System.out.println(); System.out.flush(); } }
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.
#Kotlin
Kotlin
// version 1.2.0   val board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ." val digits = "0123456789" val rows = " 26" val escape = "62" val key = "0452"   fun encrypt(message: String): String { val msg = message.toUpperCase() .filter { (it in board || it in digits) && it !in " /" } val sb = StringBuilder() for (c in msg) { val idx = board.indexOf(c) if (idx > -1) { val row = idx / 10 val col = idx % 10 sb.append(if (row == 0) "$col" else "${rows[row]}$col") } else { sb.append("$escape$c") } } val enc = sb.toString().toCharArray() for ((i, c) in enc.withIndex()) { val k = key[i % 4] - '0' if (k == 0) continue val j = c - '0' enc[i] = '0' + ((j + k) % 10) } return String(enc) }   fun decrypt(encoded: String): String { val enc = encoded.toCharArray() for ((i, c) in enc.withIndex()) { val k = key[i % 4] - '0' if (k == 0) continue val j = c - '0' enc[i] = '0' + if (j >= k) (j - k) % 10 else (10 + j - k) % 10 } val len = enc.size val sb = StringBuilder() var i = 0 while (i < len) { val c = enc[i] val idx = rows.indexOf(c) if (idx == -1) { val idx2 = c - '0' sb.append(board[idx2]) i++ } else if ("$c${enc[i + 1]}" == escape) { sb.append(enc[i + 2]) i += 3 } else { val idx2 = idx * 10 + (enc[i + 1] - '0') sb.append(board[idx2]) i += 2 } } return sb.toString() }   fun main(args: Array<String>) { val messages = listOf( "Attack at dawn", "One night-it was on the twentieth of March, 1888-I was returning", "In the winter 1965/we were hungry/just barely alive", "you have put on 7.5 pounds since I saw you.", "The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour." ) for (message in messages) { val encrypted = encrypt(message) val decrypted = decrypt(encrypted) println("\nMessage  : $message") println("Encrypted : $encrypted") println("Decrypted : $decrypted") } }
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
#Perl
Perl
use strict; use warnings; use bigint; use feature 'say'; use feature 'state'; no warnings 'recursion'; use List::Util qw(max);   sub Stirling1 { my($n, $k) = @_; return 1 unless $n || $k; return 0 unless $n && $k; state %seen; return ($seen{"{$n-1}|{$k-1}"} //= Stirling1($n-1, $k-1)) + ($seen{"{$n-1}|{$k}" } //= Stirling1($n-1, $k )) * ($n-1) }   my $upto = 12; my $width = 1 + length max map { Stirling1($upto,$_) } 0..$upto;   say 'Unsigned Stirling1 numbers of the first kind: S1(n, k):'; print 'n\k' . sprintf "%${width}s"x(1+$upto)."\n", 0..$upto;   for my $row (0..$upto) { printf '%-3d', $row; printf "%${width}d", Stirling1($row, $_) for 0..$row; print "\n"; }   say "\nMaximum value from the S1(100, *) row:"; say max map { Stirling1(100,$_) } 0..100;
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.
#Gambas
Gambas
Public Sub Main() Dim sString As String = "Hello "   sString &= "World!" Print sString   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.
#Genie
Genie
[indent=4] /* String append, in Genie */ init str:string = "Hello" str += ", world"   print str
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.
#GlovePIE
GlovePIE
var.string="This is " var.string+="Sparta!" debug=var.string
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.
#C.23
C#
using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.Statistics;   class Program { static void RunNormal(int sampleSize) { double[] X = new double[sampleSize]; var norm = new Normal(new Random()); norm.Samples(X);   const int numBuckets = 10; var histogram = new Histogram(X, numBuckets); Console.WriteLine("Sample size: {0:N0}", sampleSize); for (int i = 0; i < numBuckets; i++) { string bar = new String('#', (int)(histogram[i].Count * 360 / sampleSize)); Console.WriteLine(" {0:0.00} : {1}", histogram[i].LowerBound, bar); } var statistics = new DescriptiveStatistics(X); Console.WriteLine(" Mean: " + statistics.Mean); Console.WriteLine("StdDev: " + statistics.StandardDeviation); Console.WriteLine(); } static void Main(string[] args) { RunNormal(100); RunNormal(1000); RunNormal(10000); } }
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.
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,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); -- Position 0 is used for storage during sorting, initialized as 0   procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move;   function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp;   package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;  
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.
#Ada
Ada
with Ada.Text_IO, Ada.Containers.Vectors;   procedure Sequence is   package Vectors is new Ada.Containers.Vectors(Index_Type => Positive, Element_Type => Positive); use type Vectors.Vector;   type Sequence is record List: Vectors.Vector; Index: Positive; -- This implements some form of "lazy evaluation": -- + List holds the elements computed, so far, it is extended -- if the user tries to "Get" an element not yet computed; -- + Index is the location of the next element under consideration end record;   function Initialize return Sequence is (List => (Vectors.Empty_Vector & 1 & 1), Index => 2);   function Get(Seq: in out Sequence; Location: Positive) return Positive is -- returns the Location'th element of the sequence -- extends Seq.List (and then increases Seq.Index) if neccessary That: Positive := Seq.List.Element(Seq.Index); This: Positive := That + Seq.List.Element(Seq.Index-1); begin while Seq.List.Last_Index < Location loop Seq.List := Seq.List & This & That; Seq.Index := Seq.Index + 1; end loop; return Seq.List.Element(Location); end Get;   S: Sequence := Initialize; J: Positive;   use Ada.Text_IO;   begin -- show first fifteen members Put("First 15:"); for I in 1 .. 15 loop Put(Integer'Image(Get(S, I))); end loop; New_Line;   -- show the index where 1, 2, 3, ... first appear in the sequence for I in 1 .. 10 loop J := 1; while Get(S, J) /= I loop J := J + 1; end loop; Put("First" & Integer'Image(I) & " at" & Integer'Image(J) & "; "); if I mod 4 = 0 then New_Line; -- otherwise, the output gets a bit too ugly end if; end loop;   -- show the index where 100 first appears in the sequence J := 1; while Get(S, J) /= 100 loop J := J + 1; end loop; Put_Line("First 100 at" & Integer'Image(J) & ".");   -- check GCDs declare function GCD (A, B : Integer) return Integer is M : Integer := A; N : Integer := B; T : Integer; begin while N /= 0 loop T := M; M := N; N := T mod N; end loop; return M; end GCD;   A, B: Positive; begin for I in 1 .. 999 loop A := Get(S, I); B := Get(S, I+1); if GCD(A, B) /= 1 then raise Constraint_Error; end if; end loop; Put_Line("Correct: The first 999 consecutive pairs are relative prime!"); exception when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ; end; end Sequence;
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.
#Julia
Julia
  function merge(stream1, stream2, T=Char) if !eof(stream1) && !eof(stream2) b1 = read(stream1, T) b2 = read(stream2, T) while !eof(stream1) && !eof(stream2) if b1 <= b2 print(b1) if !eof(stream1) b1 = read(stream1, T) end else print(b2) if !eof(stream2) b2 = read(stream2, T) end end end while !eof(stream1) print(b1) b1 = read(stream1, T) end print(b1) while !eof(stream2) print(b2) b2 = read(stream2, T) end print(b2) end end   const halpha1 = "acegikmoqsuwy" const halpha2 = "bdfhjlnprtvxz" const buf1 = IOBuffer(halpha1) const buf2 = IOBuffer(halpha2)   merge(buf1, buf2, Char) println("\nDone.")    
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.
#Kotlin
Kotlin
// version 1.2.21   import java.io.File   fun merge2(inputFile1: String, inputFile2: String, outputFile: String) { val file1 = File(inputFile1) val file2 = File(inputFile2) require(file1.exists() && file2.exists()) { "Both input files must exist" } val reader1 = file1.bufferedReader() val reader2 = file2.bufferedReader() val writer = File(outputFile).printWriter() var line1 = reader1.readLine() var line2 = reader2.readLine() while (line1 != null && line2 != null) { if (line1 <= line2) { writer.println(line1) line1 = reader1.readLine() } else { writer.println(line2) line2 = reader2.readLine() } } while (line1 != null) { writer.println(line1) line1 = reader1.readLine() } while (line2 != null) { writer.println(line2) line2 = reader2.readLine() } reader1.close() reader2.close() writer.close() }   fun mergeN(inputFiles: List<String>, outputFile: String) { val files = inputFiles.map { File(it) } require(files.all { it.exists() }) { "All input files must exist" } val readers = files.map { it.bufferedReader() } val writer = File(outputFile).printWriter() var lines = readers.map { it.readLine() }.toMutableList() while (lines.any { it != null }) { val line = lines.filterNotNull().min() val index = lines.indexOf(line) writer.println(line) lines[index] = readers[index].readLine() } readers.forEach { it.close() } writer.close() }   fun main(args:Array<String>) { val files = listOf("merge1.txt", "merge2.txt", "merge3.txt", "merge4.txt") merge2(files[0], files[1], "merged2.txt") mergeN(files, "mergedN.txt") // check it worked println(File("merged2.txt").readText()) println(File("mergedN.txt").readText()) }
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.
#Lua
Lua
  local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" } local dicE, dicD, s1, s2 = {}, {}, 0, 0   function dec( txt ) local i, numb, s, t, c = 1, false while( i < #txt ) do c = txt:sub( i, i ) if not numb then if tonumber( c ) == s1 then i = i + 1; s = string.format( "%d%s", s1, txt:sub( i, i ) ) t = dicD[s] elseif tonumber( c ) == s2 then i = i + 1; s = string.format( "%d%s", s2, txt:sub( i, i ) ) t = dicD[s] else t = dicD[c] end if t == "/" then numb = true else io.write( t ) end else io.write( c ) numb = false end i = i + 1 end print() end function enc( txt ) local c for i = 1, #txt do c = txt:sub( i, i ) if c >= "A" and c <= "Z" then io.write( dicE[c] ) elseif c >= "0" and c <= "9" then io.write( string.format( "%s%s", dicE["/"], c ) ) end end print() end function createDictionaries() for i = 1, 10 do c = brd[1]:sub( i, i ) if c == " " then if s1 == 0 then s1 = i - 1 elseif s2 == 0 then s2 = i - 1 end else dicE[c] = string.format( "%d", i - 1 ) dicD[string.format( "%d", i - 1 )] = c end end for i = 1, 10 do dicE[brd[2]:sub( i, i )] = string.format( "%d%d", s1, i - 1 ) dicE[brd[3]:sub( i, i )] = string.format( "%d%d", s2, i - 1 ) dicD[string.format( "%d%d", s1, i - 1 )] = brd[2]:sub( i, i ) dicD[string.format( "%d%d", s2, i - 1 )] = brd[3]:sub( i, i ) end end function enterText() createDictionaries() io.write( "\nEncrypt or Decrypt (E/D)? " ) d = io.read() io.write( "\nEnter the text:\n" ) txt = io.read():upper() if d == "E" or d == "e" then enc( txt ) elseif d == "D" or d == "d" then dec( txt ) end end -- entry point enterText()  
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
#Phix
Phix
with javascript_semantics include mpfr.e constant lim = 100, lim1 = lim+1, last = 12 bool unsigned = true sequence s1 = repeat(0,lim1) for n=1 to lim1 do s1[n] = mpz_inits(lim1) end for mpz_set_si(s1[1][1],1) mpz {t, m100} = mpz_inits(2) for n=1 to lim do for k=1 to n do mpz_set_si(t,n-1) mpz_mul(t,t,s1[n][k+1]) if unsigned then mpz_add(s1[n+1][k+1],s1[n][k],t) else mpz_sub(s1[n+1][k+1],s1[n][k],t) end if end for end for string s = iff(unsigned?"Uns":"S") printf(1,"%signed Stirling numbers of the first kind: S1(n, k):\n n k:",s) for i=0 to last do printf(1,"%5d ", i) end for printf(1,"\n---  %s\n",repeat('-',last*10+5)) for n=0 to last do printf(1,"%2d ", n) for k=1 to n+1 do printf(1,"%9s ",{mpz_get_str(s1[n+1][k])}) end for printf(1,"\n") end for for k=1 to lim1 do mpz s100k = s1[lim1][k] if mpz_cmp(s100k,m100) > 0 then mpz_set(m100,s100k) end if end for printf(1,"\nThe maximum S1(100,k): %s\n",shorten(mpz_get_str(m100)))
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.
#Go
Go
s := "foo" s += "bar"
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.
#Gosu
Gosu
// Example 1 var s = "a" s += "b" s += "c" print(s)   // Example 2 print("a" + "b" + "c")   // Example 3 var a = "a" var b = "b" var c = "c" print("${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.
#Groovy
Groovy
  class Append{ static void main(String[] args){ def c="Hello "; def d="world"; def e=c+d; println(e); } }  
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.
#C.2B.2B
C++
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip>   int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; //holds the sum of the randomly created numbers double mean = 0.0 ; double stddev = 0.0 ; for ( int i = 1 ; i < 10001 ; i++ ) ++normalFreq[ normDistri ( engine ) ] ; for ( auto MapIt : normalFreq ) { sum += MapIt.first * MapIt.second ; } mean = sum / 10000 ; stddev = sqrt( sum / 10000 ) ; std::cout << "The mean of the distribution is " << mean << " , the " ; std::cout << "standard deviation " << stddev << " !\n" ; std::cout << "And now the histogram:\n" ; for ( auto MapIt : normalFreq ) { std::cout << std::left << std::setw( 4 ) << MapIt.first << std::string( MapIt.second / 100 , '*' ) << std::endl ; } return 0 ; }
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.
#AutoHotkey
AutoHotkey
SetWorkingDir %A_ScriptDir% #NoEnv 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" ; This loop removes the double/multiple spaces encountered when copying+pasting the given data set: While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All ; Sort the data numerically using a space as the separator: Sort, Data,ND%A_Space%   OldStem := 0 ; Parse the data using a space as the separator, storing each new string as A_LoopField and running the loop once per string: Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1) ; AutoHotkey doesn't have a Left() function, so this does the trick. If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem) ; account for all stems which don't appear (in this example, 8) but are between the lowest and highest stems OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " " ; No Right() function either, so this returns the last character of A_LoopField (the string curently used by the parsing loop) } ; Delete the old stem and leaf file (if any), write our new contents to it, then show it: FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return   PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces ) ; If the stems are more than 2 digits long, increase the number 3 to one more than the stem length. ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }  
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.
#ALGOL_68
ALGOL 68
BEGIN # find members of the Stern-Brocot sequence: starting from 1, 1 the # # subsequent members are the previous two members summed followed by # # the previous # # iterative Greatest Common Divisor routine, returns the gcd of m and n # PROC gcd = ( INT m, n )INT: BEGIN INT a := ABS m, b := ABS n; WHILE b /= 0 DO INT new a = b; b := a MOD b; a := new a OD; a END # gcd # ; # returns an array of the Stern-Brocot sequence up to n # OP STERNBROCOT = ( INT n )[]INT: BEGIN [ 1 : IF ODD n THEN n + 1 ELSE n FI ]INT result; IF n > 0 THEN result[ 1 ] := result[ 2 ] := 1; INT next pos := 2; FOR i FROM 3 WHILE next pos < n DO INT p1 = result[ i - 1 ]; result[ next pos +:= 1 ] := p1 + result[ i - 2 ]; result[ next pos +:= 1 ] := p1 OD FI; result[ 1 : n ] END # STERNPROCOT # ; FLEX[ 1 : 0 ]INT sb := STERNBROCOT 1000; # start with 1000 elements # # if that isn't enough, more will be added later # # show the first 15 elements of the sequence # print( ( "The first 15 elements of the Stern-Brocot sequence are:", newline ) ); FOR i TO 15 DO print( ( whole( sb[ i ], -3 ) ) ) OD; print( ( newline, newline ) ); # find where the numbers 1-10 first appear # INT found 10 := 0; [ 10 ]INT pos 10; FOR i TO UPB pos 10 DO pos 10[ i ] := 0 OD; FOR i TO UPB sb WHILE found 10 < 10 DO INT sb i = sb[ i ]; IF sb i <= UPB pos 10 THEN IF pos 10[ sb i ] = 0 THEN # first occurance of this number # pos 10[ sb i ] := i; found 10 +:= 1 FI FI OD; print( ( "The first positions of 1..", whole( UPB pos 10, 0 ), " in the sequence are:", newline ) ); FOR i TO UPB pos 10 DO print( ( whole( i, -2 ), ":", whole( pos 10[ i ], 0 ), " " ) ) OD; print( ( newline, newline ) ); # find where the number 100 first appears # BOOL found 100 := FALSE; FOR i WHILE NOT found 100 DO IF i > UPB sb THEN # need more elements # sb := STERNBROCOT ( UPB sb * 2 ) FI; IF sb[ i ] = 100 THEN print( ( "100 first appears at position ", whole( i, 0 ), newline, newline ) ); found 100 := TRUE FI OD; # check that the pairs of elements up to 1000 are coprime # BOOL all coprime := TRUE; FOR i FROM 2 TO 1000 WHILE all coprime DO all coprime := gcd( sb[ i ], sb[ i - 1 ] ) = 1 OD; print( ( "Element pairs up to 1000 are ", IF all coprime THEN "" ELSE "NOT " FI, "coprime", newline ) ) 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.
#Nim
Nim
import streams,strutils let stream1 = newFileStream("file1") stream2 = newFileStream("file2") while not stream1.atEnd and not stream2.atEnd: echo (if stream1.peekLine.parseInt > stream2.peekLine.parseInt: stream2.readLine else: stream1.readLine)   for line in stream1.lines: echo line for line in stream2.lines: echo line
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.
#Perl
Perl
use strict; use warnings; use English; use String::Tokenizer; use Heap::Simple;   my $stream1 = <<"END_STREAM_1"; Integer vel neque ligula. Etiam a ipsum a leo eleifend viverra sit amet ac arcu. Suspendisse odio libero, ullamcorper eu sem vitae, gravida dignissim ipsum. Aenean tincidunt commodo feugiat. Nunc viverra dolor a tincidunt porta. Ut malesuada quis mauris eget vestibulum. Fusce sit amet libero id augue mattis auctor et sit amet ligula. END_STREAM_1   my $stream2 = <<"END_STREAM_2"; In luctus odio nulla, ut finibus elit aliquet in. In auctor vitae purus quis tristique. Mauris sed erat pulvinar, venenatis lectus auctor, malesuada neque. Integer a hendrerit tortor. Suspendisse aliquet pellentesque lorem, nec tincidunt arcu aliquet non. Phasellus eu diam massa. Integer vitae volutpat augue. Nulla condimentum consectetur ante, ut consequat lectus suscipit eget. END_STREAM_2   my $stream3 = <<"END_STREAM_3"; In hendrerit eleifend mi nec ultricies. Vestibulum euismod, tellus sit amet eleifend ultrices, velit nisi dignissim lectus, non vestibulum sem nisi sed mi. Nulla scelerisque ut purus sed ultricies. Donec pulvinar eleifend malesuada. In viverra faucibus enim a luctus. Vivamus tellus erat, congue quis quam in, lobortis varius mi. Nulla ante orci, porttitor id dui ac, iaculis consequat ligula. END_STREAM_3   my $stream4 = <<"END_STREAM_4"; Suspendisse elementum nunc ex, ac pulvinar mauris finibus sed. Ut non ex sed tortor ultricies feugiat non at eros. Donec et scelerisque est. In vestibulum fringilla metus eget varius. Aenean fringilla pellentesque massa, non ullamcorper mi commodo non. Sed aliquam molestie congue. Nunc lobortis turpis at nunc lacinia, id laoreet ipsum bibendum. END_STREAM_4   my $stream5 = <<"END_STREAM_5"; Donec sit amet urna nulla. Duis nec consectetur lacus, et viverra ex. Aliquam lobortis tristique hendrerit. Suspendisse viverra vehicula lorem id gravida. Pellentesque at ligula lorem. Cras gravida accumsan lacus sit amet tincidunt. Curabitur quam nisi, viverra vel nulla vel, rhoncus facilisis massa. Aliquam erat volutpat. END_STREAM_5   my $stream6 = <<"END_STREAM_6"; Curabitur nec enim eu nisi maximus suscipit rutrum non sem. Donec lobortis nulla et rutrum bibendum. Duis varius, tellus in commodo gravida, lorem neque finibus quam, sagittis elementum leo mauris sit amet justo. Sed vestibulum velit eget sapien bibendum, sit amet porta lorem fringilla. Morbi bibendum in turpis ac blandit. Mauris semper nibh nec dignissim dapibus. Proin sagittis lacus est. END_STREAM_6   merge_two_streams(map {String::Tokenizer->new($ARG)->iterator()} ($stream1, $stream2)); merge_N_streams(6, map {String::Tokenizer->new($ARG)->iterator()} ($stream1, $stream2, $stream3, $stream4, $stream5, $stream6)); exit 0;   sub merge_two_streams { my ($iter1, $iter2) = @ARG; print "Merge of 2 streams:\n"; while (1) { if (!$iter1->hasNextToken() && !$iter2->hasNextToken()) { print "\n\n"; last; } elsif (!$iter1->hasNextToken()) { print $iter2->nextToken(), q{ }; } elsif (!$iter2->hasNextToken()) { print $iter1->nextToken(), q{ }; } elsif ($iter1->lookAheadToken() lt $iter2->lookAheadToken()) { print $iter1->nextToken(), q{ }; } else { print $iter2->nextToken(), q{ }; } } return; }   sub merge_N_streams { my $N = shift; print "Merge of $N streams:\n"; my @iters = @ARG; my $heap = Heap::Simple->new(order => 'lt', elements => 'Array'); for (my $i=0; $i<$N; $i++) { my $iter = $iters[$i]; $iter->hasNextToken() or die "Each stream must have >= 1 element"; $heap->insert([$iter->nextToken() . q{ }, $i]); } $heap->count == $N or die "Problem with initial population of heap"; while (1) { my ($token, $iter_idx) = @{ $heap->extract_top }; print $token; # Attempt to read the next element from the same iterator where we # obtained the element we just extracted. my $to_insert = _fetch_next_element($iter_idx, $N, @iters); if (! $to_insert) { print join('', map {$ARG->[0]} $heap->extract_all); last; } $heap->insert($to_insert); } return; }   sub _fetch_next_element { my $starting_idx = shift; my $N = shift; my @iters = @ARG; # Go round robin through every iterator exactly once, returning the first # element on offer. my @round_robin_idxs = map {$ARG % $N} ($starting_idx .. $starting_idx + $N - 1); foreach my $iter_idx (@round_robin_idxs) { my $iter = $iters[$iter_idx]; if ($iter->hasNextToken()) { return [$iter->nextToken() . q{ }, $iter_idx]; } } # At this point every iterator has been exhausted. return; }
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.
#M2000_Interpreter
M2000 Interpreter
  module Straddling_checkerboard { function encrypt$(message$, alphabet) { message$=filter$(ucase$(message$),"-/,. ") def num1, num2 num1=instr(alphabet#val$(0)," ") num2=instr(alphabet#val$(0)," ", num1+1)-1 num1-- escapenum=instr(alphabet#val$(2),"/")-1 escapenum1=instr(alphabet#val$(2),".")-1 num0=-10 num10=num1*10-20 num20=num2*10-30 numbers=(escapenum+num2*10)*10 numbers1=(escapenum1+num2*10)*10 boardrow=each(alphabet) cipherkey$="0123456789" : while boardrow :cipherkey$+=array$(boardrow) :end while encoded$="" for i=1 to len(message$) n=instr(cipherkey$, mid$(message$,i,1))-1 if n<10 then n+=if(random(10)<5->numbers, numbers1) else.if n<20 then n+=num0 else.if n<30 then n+=num10 else n+=num20 end if encoded$+=str$(n,"") next =encoded$ } function decrypt$(encoded$, alphabet) { def num1, num2 num1=instr(alphabet#val$(0)," ") num2=instr(alphabet#val$(0)," ", num1+1)-1 num1-- escapenum=instr(alphabet#val$(2),"/")-1 escapenum1=instr(alphabet#val$(2),".")-1 def i=1, decoded$ j=len(encoded$)+1 while i<j m=val(mid$(encoded$,i,1)) if m=num1 then decoded$+=mid$(alphabet#val$(1), val(mid$(encoded$,i+1,1))+1,1) i++ else.if m=num2 then if i+1<j then mm=val(mid$(encoded$,i+1,1)) if mm=escapenum or mm=escapenum1 then decoded$+=mid$(encoded$,i+2,1) i+=2 else decoded$+=mid$(alphabet#val$(2), val(mid$(encoded$,i+1,1))+1,1) i++ end if else decoded$+=mid$(alphabet#val$(2), val(mid$(encoded$,i+1,1))+1,1) i++ end if else decoded$+=mid$(alphabet#val$(0), m+1,1) end if i++ end while =decoded$ } Module DisplayBoard (alphabet, &Doc$){ num1=instr(alphabet#val$(0)," ") num2=instr(alphabet#val$(0)," ", num1+1)-1 num1-- escapenum=instr(alphabet#val$(2),"/")-1 escapenum1=instr(alphabet#val$(2),".")-1 \\ display straddling checkerboard checkerboard =cons(("0123456789",),alphabet) labels=(" "," ",str$(num1,""), str$(num2,"")) disp=each(checkerboard) while disp Doc$=labels#val$(disp^)+" "+array$(disp)+{ } end while } Document Doc$ Const nl$={ } Function OnePad$(Message$, PadSerial, n=1) { x=random(!PadSerial) ' push old seed, set the new one encoded$="" for i=1 to len(Message$) encoded$+=str$((val(mid$(Message$,i,1))+10+n*random(1, 10))mod 10,"") next i x=random(!) ' restore old seed =encoded$ } \\ select a random alphabet select case random(1,3) case 1 alphabet=("ESTONIAR ","BCDFGHJKLM","/PQUVWXYZ.") : Doc$="First "+nl$ case 2 alphabet=("ET AON RIS","BCDFGHJKLM","PQ/UVWXYZ.") : Doc$="Second"+nl$ case 3 alphabet=("ESTONIAR ","BCDFGHJKLM","PQU.VWXYZ/") : Doc$="Third"+nl$ end select DisplayBoard alphabet, &Doc$ msg$="One night-it was on the twentieth of March, 1888-I was returning" Doc$= "original message:"+nl$ Doc$= msg$+nl$ Doc$= "encrypted message:"+nl$ crypt$=encrypt$(msg$, alphabet) Doc$=crypt$+nl$ serial=random(1234567,9345678) Doc$= "encrypted message using one pad using serial:"+str$(serial)+nl$ crypt$=OnePad$(crypt$, serial) Doc$=crypt$+nl$ Doc$= "decrypted message using one pad:"+nl$ crypt$=OnePad$(crypt$, serial,-1) Doc$=crypt$+nl$ Doc$= "decrypted message:"+nl$ Doc$=decrypt$(crypt$, alphabet) Print #-2, Doc$ ' render to console using new lines codes from Doc$ Clipboard Doc$ } Straddling_checkerboard  
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.
#Nim
Nim
import strutils, tables   const FullStop = '.' Escape = '/'   type Checkerboard = object encryptTable: Table[char, string] decryptTable: Table[string, char]     proc initCheckerboard(digits: string; row1, row2, row3: string): Checkerboard = ## Initialize a checkerboard with given digits in row 0 and the following given rows. ## No sanity check is performed.   var rowChars: seq[char] # The two characters to use to identify rows 2 and 3.   # Process row 1. for col, ch in row1: if ch == ' ': rowChars.add digits[col] else: result.encryptTable[ch] = $digits[col] if rowChars.len != 2: raise newException(ValueError, "expected two blank spots in first letter row.")   # Add rows 2 and 3. for col, ch in row2: result.encryptTable[ch] = rowChars[0] & digits[col] for col, ch in row3: result.encryptTable[ch] = rowChars[1] & digits[col] if Escape notin result.encryptTable: raise newException(ValueError, "missing Escape character.")   # Build decrypt table from encrypt table. for c, s in result.encryptTable.pairs: result.decryptTable[s] = c     proc encrypt(board: Checkerboard; message: string): string = ## Encrypt a string.   let message = message.toUpperAscii for ch in message: case ch of 'A'..'Z', FullStop, Escape: result.add board.encryptTable[ch] of '0'..'9': result.add board.encryptTable[Escape] result.add ch else: discard # Ignore other characters.     proc raiseError() = ## Raise a ValueError to signal a corrupt message. raise newException(ValueError, "corrupt message")     proc decrypt(board: Checkerboard; message: string): string = ## Decrypt a message.   var escaped = false # Escape char previously encountered. var str = "" # Current sequence of characters (contains 0, 1 or 2 chars).   for ch in message: if ch notin '0'..'9': raiseError()   if escaped: # Digit is kept as is. result.add ch escaped = false else: # Try to decrypt this new digit. str.add ch if str in board.decryptTable: let c = board.decryptTable[str] if c == Escape: escaped = true else: result.add c str.setLen(0) elif str.len == 2: # Illegal combination of two digits. raiseError()   when isMainModule: let board = initCheckerboard("8752390146", "ET AON RIS", "BC/FGHJKLM", "PQD.VWXYZU") let message = "you have put on 7.5 pounds since I saw you." echo "Message: ", message let crypted = board.encrypt(message) echo "Crypted: ", crypted echo "Decrypted: ", board.decrypt(crypted)
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
#Prolog
Prolog
:- dynamic stirling1_cache/3.   stirling1(N, N, 1):-!. stirling1(_, 0, 0):-!. stirling1(N, K, 0):- K > N, !. stirling1(N, K, L):- stirling1_cache(N, K, L), !. stirling1(N, K, L):- N1 is N - 1, K1 is K - 1, stirling1(N1, K, L1), stirling1(N1, K1, L2), !, L is L2 + (N - 1) * L1, assertz(stirling1_cache(N, K, L)).   print_stirling_numbers(N):- between(1, N, K), stirling1(N, K, L), writef('%10r', [L]), fail. print_stirling_numbers(_):- nl.   print_stirling_numbers_up_to(M):- between(1, M, N), print_stirling_numbers(N), fail. print_stirling_numbers_up_to(_).   max_stirling1(N, Max):- aggregate_all(max(L), (between(1, N, K), stirling1(N, K, L)), Max).   main:- writeln('Unsigned Stirling numbers of the first kind up to S1(12,12):'), print_stirling_numbers_up_to(12), writeln('Maximum value of S1(n,k) where n = 100:'), max_stirling1(100, M), writeln(M).
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.
#Haskell
Haskell
  main = putStrLn ("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.
#Icon_and_Unicon
Icon and Unicon
  procedure main() s := "foo" s ||:= "bar" write(s) end  
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.
#D
D
import std.stdio, std.random, std.math, std.range, std.algorithm, statistics_basic;   struct Normals { double mu, sigma; double[2] state; size_t index = state.length; enum empty = false;   void popFront() pure nothrow { index++; }   @property double front() { if (index >= state.length) { immutable r = sqrt(-2 * uniform!"]["(0., 1.0).log) * sigma; immutable x = 2 * PI * uniform01; state = [mu + r * x.sin, mu + r * x.cos]; index = 0; } return state[index]; } }   void main() { const data = Normals(0.0, 0.5).take(100_000).array; writefln("Mean: %8.6f, SD: %8.6f\n", data.meanStdDev[]); data.map!q{ max(0.0, min(0.9999, a / 3 + 0.5)) }.showHistogram01; }
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.
#AWK
AWK
  # syntax: GAWK -f STEM-AND-LEAF_PLOT.AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { 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" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }  
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.
#ALGOL-M
ALGOL-M
begin integer array S[1:1200]; integer i,ok;   integer function gcd(a,b); integer a,b; gcd := if a>b then gcd(a-b,b) else if a<b then gcd(a,b-a) else a;   integer function first(n); integer n; begin integer i; i := 1; while S[i]<>n do i := i + 1; first := i; end;   S[1] := S[2] := 1; for i := 2 step 1 until 600 do begin S[i*2-1] := S[i] + S[i-1]; S[i*2] := S[i]; end;   write("First 15 numbers:"); for i := 1 step 1 until 15 do begin if i-i/5*5=1 then write(S[i]) else writeon(S[i]); end;   write(""); write("First occurrence:"); for i := 1 step 1 until 10 do write(i, " at", first(i)); write(100, " at", first(100));   ok := 1; for i := 1 step 1 until 999 do begin if gcd(S[i], S[i+1]) <> 1 then begin write("gcd",S[i],",",S[i+1],"<> 1"); ok := 0; end; end; if ok = 1 then write("The GCD of each pair of consecutive members is 1."); 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.
#Phix
Phix
without js -- file i/o include builtins/pqueue.e procedure add(integer fn, pq) object line = gets(fn) if line=-1 then close(fn) else pq_add({fn,line}, pq) end if end procedure -- setup (optional/remove if files already exist) constant data = {"Line 001\nLine 008\nLine 017\n", "Line 019\nLine 033\nLine 044\nLine 055\n", "Line 019\nLine 029\nLine 039\n", "Line 023\nLine 030\n"}, filenames = {"file1.txt","file2.txt","file3.txt","file4.txt"} -- (or command_line()[3..$] if you prefer) for i=1 to length(filenames) do integer fn = open(filenames[i], "w") if fn<0 then crash("cannot open file") end if puts(fn, data[i]) close(fn) end for -- initilisation integer pq = pq_new() for i=1 to length(filenames) do integer fn = open(filenames[i], "r") if fn<0 then crash("cannot open file") end if add(fn,pq) end for -- main loop while not pq_empty(pq) do {integer fn, string line} = pq_pop(pq) puts(1,line) add(fn, pq) end while pq_destroy(pq) -- cleanup (optional/remove if files already exist) for i=1 to length(filenames) do {} = delete_file(filenames[i]) end for
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.
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util <min max>;   my(%encode,%decode,@table);   sub build { my($u,$v,$alphabet) = @_; my(@flat_board,%p2c,%c2p); my $numeric_escape = '/';   @flat_board = split '', uc $alphabet; splice @flat_board, min($u,$v), 0, undef; splice @flat_board, max($u,$v), 0, undef;   push @table, [' ', 0..9]; push @table, [' ', map { defined $_ ? $_ : ' '} @flat_board[ 0 .. 9] ]; push @table, [$u, @flat_board[10 .. 19]]; push @table, [$v, @flat_board[20 .. 29]];   my @nums = my @order = 0..9; push @nums, (map { +"$u$_" } @order), map { +"$v$_" } @order;   @c2p{@nums} = @flat_board; for (keys %c2p) { delete $c2p{$_} unless defined $c2p{$_} } @p2c{values %c2p} = keys %c2p; $p2c{$_} = $p2c{$numeric_escape} . $_ for 0..9; while (my ($k, $v) = each %p2c) { $encode{$k} = $v; $decode{$v} = $k unless $k eq $numeric_escape; } }   sub decode { my($string) = @_; my $keys = join '|', keys %decode; $string =~ s/($keys)/$decode{$1}/gr; }   sub encode { my($string) = uc shift; $string =~ s#(.)#$encode{$1} // $encode{'.'}#ger; }   my $sc = build(3, 7, 'HOLMESRTABCDFGIJKNPQUVWXYZ./'); say join ' ', @$_ for @table; say ''; say 'Original: ', my $original = 'One night-it was on the twentieth of March, 1888-I was returning'; say 'Encoded: ', my $en = encode($original); say 'Decoded: ', decode($en);
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
#PureBasic
PureBasic
EnableExplicit #MAX=12 #LZ=10 #SP$=" " Dim s1.i(#MAX,#MAX) Define n.i,k.i,x.i,s$,esc$   s1(0,0)=1 esc$=#ESC$+"[8;24;170t" ; Enlarges the console window   For n=0 To #MAX For k=1 To n s1(n,k)=s1(n-1,k-1)-(n-1)*s1(n-1,k) Next Next   If OpenConsole() Print(esc$) PrintN(~"Signed Stirling numbers of the first kind\n") Print(#SP$+"k") For x=0 To #MAX : Print(#SP$+RSet(Str(x),#LZ)) : Next PrintN(~"\n n"+LSet("-",13*12,"-")) For n=0 To #MAX Print(RSet(Str(n),3)) For k=0 To #MAX : Print(#SP$+RSet(Str(s1(n,k)),#LZ)) : Next PrintN("") Next Input() 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
#Python
Python
  computed = {}   def sterling1(n, k): key = str(n) + "," + str(k)   if key in computed.keys(): return computed[key] if n == k == 0: return 1 if n > 0 and k == 0: return 0 if k > n: return 0 result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k) computed[key] = result return result   print("Unsigned Stirling numbers of the first kind:") MAX = 12 print("n/k".ljust(10), end="") for n in range(MAX + 1): print(str(n).rjust(10), end="") print() for n in range(MAX + 1): print(str(n).ljust(10), end="") for k in range(n + 1): print(str(sterling1(n, k)).rjust(10), end="") print() print("The maximum value of S1(100, k) = ") previous = 0 for k in range(1, 100 + 1): current = sterling1(100, k) if current > previous: previous = current else: print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), 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.
#J
J
s=: 'new' s new s=: s,' value' NB. append is in-place s new value
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.
#Java
Java
String sa = "Hello"; sa += ", World!"; System.out.println(sa);   StringBuilder ba = new StringBuilder(); ba.append("Hello"); ba.append(", World!"); System.out.println(ba.toString());
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.
#Elixir
Elixir
defmodule Statistics do def normal_distribution(n, w\\5) do {sum, sum2, hist} = generate(n, w) mean = sum / n stddev = :math.sqrt(sum2 / n - mean*mean)   IO.puts "size: #{n}" IO.puts "mean: #{mean}" IO.puts "stddev: #{stddev}" {min, max} = Map.to_list(hist) |> Enum.filter_map(fn {_k,v} -> v >= n/120/w end, fn {k,_v} -> k end) |> Enum.min_max Enum.each(min..max, fn i -> bar = String.duplicate("=", trunc(120 * w * Map.get(hist, i, 0) / n))  :io.fwrite "~4.1f: ~s~n", [i/w, bar] end) IO.puts "" end   defp generate(n, w) do Enum.reduce(1..n, {0, 0, %{}}, fn _,{sum, sum2, hist} -> z = :rand.normal {sum+z, sum2+z*z, Map.update(hist, round(w*z), 1, &(&1+1))} end) end end   Enum.each([100,1000,10000], fn n -> Statistics.normal_distribution(n) end)
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.
#Factor
Factor
USING: assocs formatting kernel math math.functions math.statistics random sequences sorting ;   2,000,000 [ 0 1 normal-random-float ] replicate  ! make data set dup [ mean ] [ population-std ] bi  ! calculate and show "Mean: %f\nStdev: %f\n\n" printf  ! mean and stddev   [ 10 * floor 10 / ] map  ! map data to buckets histogram >alist [ first ] sort-with  ! create histogram sorted by bucket (key) dup values supremum  ! find maximum count [ [ /f 100 * >integer ] keepd  ! how big should this histogram bar be? [ [ CHAR: * ] "" replicate-as ] dip  ! make the bar "% 5.2f: %s  %d\n" printf  ! print a line of the histogram ] curry assoc-each
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0)   DIM Data%(120) 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   PROCleafplot(Data%(), DIM(Data%(),1) + 1) END   DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2   C% = n% CALL Sort%, x%(0)   i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
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.
#Amazing_Hopper
Amazing Hopper
  #include <flow.h> #include <flow-flow.h>   DEF-MAIN(argv,argc) CLR-SCR SET( amount, 1200 ) DIM(amount) AS-ONES( Stern )   /* Generate Stern-Brocot sequence: */ GOSUB( Generate Sequence ) PRNL( "Find 15 first: ", [1:19] CGET(Stern) )   /* show Stern-Brocot sequence: */ SET( i, 1 ), ITERATE( ++i, LE?(i,10), \ PRN( "First ",i," at "), {i} GOSUB( Find First ), PRNL ) PRN( "First 100 at "), {100} GOSUB( Find First ), PRNL   /* check GCD: */ ODD-POS, CGET(Stern), EVEN-POS, CGET(Stern), COMP-GCD, GET-SUMMATORY, DIV-INTO( DIV(amount,2) )   IF ( IS-EQ?(1), PRNL("The GCD of every pair of adjacent elements is 1"),\ PRNL("Stern-Brocot Sequence is wrong!") ) END   RUTINES   DEF-FUN(Find First, n ) RET ( SCAN(1, n, Stern) )   DEF-FUN(Generate Sequence) SET(i,2) FOR( LE?(i, DIV(amount,2)), ++i ) [i] GET( Stern ), [ MINUS-ONE(i) ] GET( Stern ), ADD-IT [ SUB(MUL(i,2),1) ] CPUT( Stern ) [i] GET( Stern ), [MUL(i,2)] CPUT( Stern ) NEXT RET  
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.
#PicoLisp
PicoLisp
(de streamMerge @ (let Heap (make (while (args) (let? Fd (next) (if (in Fd (read)) (link (cons @ Fd)) (close Fd) ) ) ) ) (make (while Heap (link (caar (setq Heap (sort Heap)))) (if (in (cdar Heap) (read)) (set (car Heap) @) (close (cdr (pop 'Heap))) ) ) ) ) )
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.
#Python
Python
import heapq import sys   sources = sys.argv[1:] for item in heapq.merge(open(source) for source in sources): print(item)
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
#11l
11l
V 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’]   states = sorted(states)   DefaultDict[String, [String]] smap L(s1) states[0 .< (len)-1] V i = L.index L(s2) states[i+1..] smap[sorted(s1‘’s2).join(‘’)].append(s1‘ + ’s2)   L(pairs) sorted(smap.values()) I pairs.len > 1 print(pairs.join(‘ = ’))
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.
#6502_Assembly
6502 Assembly
with Ada.Text_IO; procedure Foo is begin Ada.Text_IO.Put_Line("Bar"); end Foo;
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.
#Phix
Phix
with javascript_semantics function read_table(string cb) sequence encode = repeat("",128), decode = repeat(0,128), row = {0} if length(cb)!=30 then crash("table wrong length") end if for i=1 to 30 do integer c = cb[i] if c=' ' then row &= i-1 else integer code = row[floor((i-1)/10)+1]*10+mod((i-1),10) encode[c] = sprintf("%d",code) decode[code+1] = c end if end for return {encode, decode} end function function encipher(sequence encode, string s, bool strip=false) string res = "" for i=1 to length(s) do integer c = upper(s[i]), code if c>='0' and c<='9' then res &= encode['.']&c elsif c>='A' and c<='Z' then res &= encode[c] elsif not strip or c='/' then -- (see note) res &= encode['/'] end if end for return res end function function decipher(sequence decode, string s, bool strip=false) string res = "" integer i = 1 while i<=length(s) do integer c = s[i]-'0'+1 if decode[c]=0 then i += 1 c = (c-1)*10+s[i]-'0'+1 end if integer d = decode[c] if d='.' then i += 1 d = s[i] elsif d='/' and not strip then -- (see note) d = ' ' end if res &= d i += 1 end while return res end function constant cb = "ET AON RIS"& "BCDFGHJKLM"& "PQ/UVWXYZ." sequence {encode,decode} = read_table(cb) -- Note there is a subtle difference in space handling, to exactly match other outputs try -- {encode,decode} = read_table("HOL MES RTABCDFGIJKNPQUVWXYZ/.") instead of -- {encode,decode} = read_table("HOL MES RTABCDFGIJKNPQUVWXYZ./"), and -- {encode,decode} = read_table("ET AON RISBCDFGHJKLMPQ.UVWXYZ/") instead of -- {encode,decode} = read_table("ET AON RISBCDFGHJKLMPQ/UVWXYZ.") string msg = "In the winter 1965/we were hungry/just barely alive" printf(1,"message: %s\n", {msg}) string enc = encipher(encode, msg), dec = decipher(decode, enc) printf(1,"encoded: %s\n", {enc}) printf(1,"decoded: %s\n", {dec}) printf(1,"\nNo spaces:\n") enc = encipher(encode, msg, true) dec = decipher(decode, enc, true) printf(1,"encoded: %s\n", {enc}) printf(1,"decoded: %s\n", {dec})
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
#Quackery
Quackery
[ dip number$ over size - space swap of swap join echo$ ] is justify ( n n --> )   [ table ] is s1table ( n --> n )   [ swap 101 * + s1table ] is s1 ( n n --> n )   101 times [ i^ 101 times [ dup i^ [ over 0 = over 0 = and iff [ 2drop 1 ] done over 0 > over 0 = and iff [ 2drop 0 ] done 2dup < iff [ 2drop 0 ] done 2dup 1 - swap 1 - swap s1 unrot dip [ 1 - dup ] s1 * + ] ' s1table put ] drop ]   say "Unsigned Stirling numbers of the first kind." cr cr 13 times [ i^ dup 1+ times [ dup i^ s1 10 justify ] drop cr ] cr 0 100 times [ 100 i^ 1+ s1 max ] echo cr
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
#Raku
Raku
sub Stirling1 (Int \n, Int \k) { return 1 unless n || k; return 0 unless n && k; state %seen; (%seen{"{n - 1}|{k - 1}"} //= Stirling1(n - 1, k - 1)) + (n - 1) * (%seen{"{n - 1}|{k}"} //= Stirling1(n - 1, k)) }   my $upto = 12;   my $mx = (1..^$upto).map( { Stirling1($upto, $_) } ).max.chars;   put 'Unsigned Stirling numbers of the first kind: S1(n, k):'; put 'n\k', (0..$upto)».fmt: "%{$mx}d";   for 0..$upto -> $row { $row.fmt('%-3d').print; put (0..$row).map( { Stirling1($row, $_) } )».fmt: "%{$mx}d"; }   say "\nMaximum value from the S1(100, *) row:"; say (^100).map( { Stirling1 100, $_ } ).max;
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.
#JavaScript
JavaScript
var s1 = "Hello"; s1 += ", World!"; print(s1);   var s2 = "Goodbye"; // concat() returns the strings together, but doesn't edit existing string // concat can also have multiple parameters print(s2.concat(", 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.
#jq
jq
"Hello" | . += ", world!"   ["Hello"] | .[0] += ", world!" | .[0]   { "greeting": "Hello"} | .greeting += ", world!" | .greeting
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.
#Fortran
Fortran
program Normal_Distribution implicit none   integer, parameter :: i64 = selected_int_kind(18) integer, parameter :: r64 = selected_real_kind(15) integer(i64), parameter :: samples = 1000000_i64 real(r64) :: mean, stddev real(r64) :: sumn = 0, sumnsq = 0 integer(i64) :: n = 0 integer(i64) :: bin(-50:50) = 0 integer :: i, ind real(r64) :: ur1, ur2, nr1, nr2, s   n = 0 do while(n <= samples) call random_number(ur1) call random_number(ur2) ur1 = ur1 * 2.0 - 1.0 ur2 = ur2 * 2.0 - 1.0   s = ur1*ur1 + ur2*ur2 if(s >= 1.0_r64) cycle   nr1 = ur1 * sqrt(-2.0*log(s)/s) ind = floor(5.0*nr1) bin(ind) = bin(ind) + 1_i64 sumn = sumn + nr1 sumnsq = sumnsq + nr1*nr1   nr2 = ur2 * sqrt(-2.0*log(s)/s) ind = floor(5.0*nr2) bin(ind) = bin(ind) + 1_i64 sumn = sumn + nr2 sumnsq = sumnsq + nr2*nr2 n = n + 2_i64 end do   mean = sumn / n stddev = sqrt(sumnsq/n - mean*mean)   write(*, "(a, i0)") "sample size = ", samples write(*, "(a, f17.15)") "Mean : ", mean, write(*, "(a, f17.15)") "Stddev : ", stddev   do i = -15, 15 write(*, "(f4.1, a, a)") real(i)/5.0, ": ", repeat("=", int(bin(i)*500/samples)) end do   end program
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
C
#include <stdio.h> #include <stdlib.h>   int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; }   void leaf_plot(int *x, int len) { int i, j, d;   qsort(x, len, sizeof(int), icmp);   i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } }   int main() { int 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 };   leaf_plot(data, sizeof(data)/sizeof(data[0]));   return 0; }
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.
#APL
APL
task←{ stern←{⍵{ ⍺←0 ⋄ ⍺⍺≤⍴⍵:⍺⍺↑⍵ (⍺+1)∇⍵,(+/,2⊃⊣)2↑⍺↓⍵ }1 1} seq←stern 1200 ⍝ Cache 1200 elements ⎕←'First 15 elements:',15↑seq ⎕←'Locations of 1..10:',seq⍳⍳10 ⎕←'Location of 100:',seq⍳100 ⎕←'All GCDs 1:','no' 'yes'[1+1∧.=2∨/1000↑seq] }
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.
#Racket
Racket
;; This module produces a sequence that merges streams in order (by <) #lang racket/base (require racket/stream)   (define-values (tl-first tl-rest tl-empty?) (values stream-first stream-rest stream-empty?))   (define-struct merged-stream (< ss v ss′) #:mutable ; sadly, so we don't have to redo potentially expensive < #:methods gen:stream [(define (stream-empty? S)  ;; andmap defined to be true when ss is null (andmap tl-empty? (merged-stream-ss S)))   (define (cache-next-head S) (unless (box? (merged-stream-v S)) (define < (merged-stream-< S)) (define ss (merged-stream-ss S)) (define-values (best-f best-i) (for/fold ((F #f) (I 0)) ((s (in-list ss)) (i (in-naturals))) (if (tl-empty? s) (values F I) (let ((f (tl-first s))) (if (or (not F) (< f (unbox F))) (values (box f) i) (values F I)))))) (set-merged-stream-v! S best-f) (define ss′ (for/list ((s ss) (i (in-naturals)) #:unless (tl-empty? s)) (if (= i best-i) (tl-rest s) s))) (set-merged-stream-ss′! S ss′)) S)   (define (stream-first S) (cache-next-head S) (unbox (merged-stream-v S)))   (define (stream-rest S) (cache-next-head S) (struct-copy merged-stream S [ss (merged-stream-ss′ S)] [v #f]))])   (define ((merge-sequences <) . sqs) (let ((strms (map sequence->stream sqs))) (merged-stream < strms #f #f)))   ;; --------------------------------------------------------------------------------------------------- (module+ main (require racket/string)  ;; there are file streams and all sorts of other streams -- we can even read lines from strings (for ((l ((merge-sequences string<?) (in-lines (open-input-string "aardvark dog fox")) (in-list (string-split "cat donkey elephant")) (in-port read (open-input-string #<<< "boy" "emu" "monkey" < ))))) (displayln l)))   ;; --------------------------------------------------------------------------------------------------- (module+ test (require rackunit) (define merge-sequences/< (merge-sequences <))   (check-equal? (for/list ((i (in-stream (merge-sequences/< (in-list '(1 3 5)))))) i) '(1 3 5))  ;; in-stream (and in-list) is optional (but may increase performance) (check-equal? (for/list ((i (merge-sequences/<))) i) null) (check-equal? (for/list ((i (merge-sequences/< '(1 3 5) '(2 4 6)))) i) '(1 2 3 4 5 6)) (check-equal? (for/list ((i (merge-sequences/< '(1 3 5) '(2 4 6 7 8 9 10)))) i) '(1 2 3 4 5 6 7 8 9 10)) (check-equal? (for/list ((i (merge-sequences/< '(2 4 6 7 8 9 10) '(1 3 5)))) i) '(1 2 3 4 5 6 7 8 9 10)))