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/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#D
D
import std.array : uninitializedArray; import std.bigint; import std.stdio : writeln, writefln;   auto bellTriangle(int n) { auto tri = uninitializedArray!(BigInt[][])(n); foreach (i; 0..n) { tri[i] = uninitializedArray!(BigInt[])(i); tri[i][] = BigInt(0); } tri[1][0] = 1; foreach (i; 2..n) { tri[i][0] = tri[i - 1][i - 2]; foreach (j; 1..i) { tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]; } } return tri; }   void main() { auto bt = bellTriangle(51); writeln("First fifteen and fiftieth Bell numbers:"); foreach (i; 1..16) { writefln("%2d: %d", i, bt[i][0]); } writeln("50: ", bt[50][0]); writeln; writeln("The first ten rows of Bell's triangle:"); foreach (i; 1..11) { writeln(bt[i]); } }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#CoffeeScript
CoffeeScript
fibgen = () -> a = 1; b = 0 return () -> ([a, b] = [b, a+b])[1]   leading = (x) -> x.toString().charCodeAt(0) - 0x30   f = fibgen()   benford = (0 for i in [1..9]) benford[leading(f()) - 1] += 1 for i in [1..1000]   log10 = (x) -> Math.log(x) * Math.LOG10E   actual = benford.map (x) -> x * 0.001 expected = (log10(1 + 1/x) for x in [1..9])   console.log "Leading digital distribution of the first 1,000 Fibonacci numbers" console.log "Digit\tActual\tExpected" for i in [1..9] console.log i + "\t" + actual[i - 1].toFixed(3) + '\t' + expected[i - 1].toFixed(3)
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#C.2B.2B
C++
/** * Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 * Apple LLVM version 9.1.0 (clang-902.0.39.1) * Target: x86_64-apple-darwin17.5.0 * Thread model: posix */   #include <boost/multiprecision/cpp_int.hpp> // 1024bit precision #include <boost/rational.hpp> // Rationals #include <iostream> // formatting with std::cout #include <vector> // Container   typedef boost::rational<boost::multiprecision::int1024_t> rational; // reduce boilerplate   rational bernoulli(size_t n) { auto out = std::vector<rational>();   for (size_t m = 0; m <= n; m++) { out.emplace_back(1, (m + 1)); // automatically constructs object for (size_t j = m; j >= 1; j--) { out[j - 1] = rational(j) * (out[j - 1] - out[j]); } } return out[0]; }   int main() { for (size_t n = 0; n <= 60; n += n >= 2 ? 2 : 1) { auto b = bernoulli(n); std::cout << "B(" << std::right << std::setw(2) << n << ") = "; std::cout << std::right << std::setw(44) << b.numerator(); std::cout << " / " << b.denominator() << std::endl; }   return 0; }
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#ALGOL_68
ALGOL 68
BEGIN MODE ELEMENT = STRING;   # Iterative: # PROC iterative binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: ( INT out, low := LWB hay stack, high := UPB hay stack; WHILE low < high DO INT mid := (low+high) OVER 2; IF hay stack[mid] > needle THEN high := mid-1 ELIF hay stack[mid] < needle THEN low := mid+1 ELSE out:= mid; stop iteration FI OD; low EXIT stop iteration: out ); # Recursive: # PROC recursive binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: ( IF LWB hay stack > UPB hay stack THEN LWB hay stack ELIF LWB hay stack = UPB hay stack THEN IF hay stack[LWB hay stack] = needle THEN LWB hay stack ELSE LWB hay stack FI ELSE INT mid := (LWB hay stack+UPB hay stack) OVER 2; IF hay stack[mid] > needle THEN recursive binary search(hay stack[:mid-1], needle) ELIF hay stack[mid] < needle THEN mid + recursive binary search(hay stack[mid+1:], needle) ELSE mid FI FI ); # Test cases: # test:( ELEMENT needle = "mister"; []ELEMENT hay stack = ("AA","Maestro","Mario","Master","Mattress","Mister","Mistress","ZZ"), test cases = ("A","Master","Monk","ZZZ");   PROC test search = (PROC([]ELEMENT, ELEMENT)INT search, []ELEMENT test cases)VOID: FOR case TO UPB test cases DO ELEMENT needle = test cases[case]; INT index = search(hay stack, needle); BOOL found = ( index <= 0 | FALSE | hay stack[index]=needle); print(("""", needle, """ ", (found|"FOUND at"|"near"), " index ", whole(index, 0), newline)) OD; test search(iterative binary search, test cases); test search(recursive binary search, test cases) ) END
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#BBC_BASIC
BBC BASIC
a$ = "abracadabra" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "seesaw"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "elk"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "grrrrrr"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "up"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "a"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) END   DEF FNshuffle(s$) LOCAL i%, j%, l%, s%, t%, t$ t$ = s$ : s% = !^s$ : t% = !^t$ : l% = LEN(t$) FOR i% = 0 TO l%-1 : SWAP t%?i%,t%?(RND(l%)-1) : NEXT FOR i% = 0 TO l%-1 FOR j% = 0 TO l%-1 IF i%<>j% THEN IF t%?i%<>s%?j% IF s%?i%<>t%?j% THEN SWAP t%?i%,t%?j% EXIT FOR ENDIF ENDIF NEXT NEXT i% = t$   DEF FNsame(s$, t$) LOCAL i%, n% FOR i% = 1 TO LEN(s$) IF MID$(s$,i%,1)=MID$(t$,i%,1) n% += 1 NEXT = " (" + STR$(n%) + ")"
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Bracmat
Bracmat
  ( shuffle = m car cdr todo a z count string .  !arg:(@(?:%?car ?cdr).?todo) & !Count:?count & ( @( !todo  :  ?a (%@:~!car:?m) ( ?z & shuffle$(!cdr.str$(!a !z))  : (<!count:?count.?string) & ~ ) ) | !count:<!Count | @(!todo:%?m ?z) & shuffle$(!cdr.!z):(?count.?string) & !count+1 . !m !string ) | (0.) ) & abracadabra seesaw elk grrrrrr up a:?words & whl ' ( !words:%?word ?words & @(!word:? [?Count) & out$(!word shuffle$(!word.!word)) ) & Done  
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Erlang
Erlang
-module(binary_string). -compile([export_all]).   %% Erlang has very easy handling of binary strings. Using %% binary/bitstring syntax the various task features will be %% demonstrated.     %% Erlang has GC so destruction is not shown. test() -> Binary = <<0,1,1,2,3,5,8,13>>, % binaries can be created directly io:format("Creation: ~p~n",[Binary]), Copy = binary:copy(Binary), % They can also be copied io:format("Copy: ~p~n",[Copy]), Compared = Binary =:= Copy, % They can be compared directly io:format("Equal: ~p = ~p ? ~p~n",[Binary,Copy,Compared]), Empty1 = size(Binary) =:= 0, % The empty binary would have size 0 io:format("Empty: ~p ? ~p~n",[Binary,Empty1]), Empty2 = size(<<>>) =:= 0, % The empty binary would have size 0 io:format("Empty: ~p ? ~p~n",[<<>>,Empty2]), Substring = binary:part(Binary,3,3), io:format("Substring: ~p [~b..~b] => ~p~n",[Binary,3,5,Substring]), Replace = binary:replace(Binary,[<<1>>],<<42>>,[global]), io:format("Replacement: ~p~n",[Replace]), Append = <<Binary/binary,21>>, io:format("Append: ~p~n",[Append]), Join = <<Binary/binary,<<21,34,55>>/binary>>, io:format("Join: ~p~n",[Join]).   %% Since the task also asks that we show how these can be reproduced %% rather than just using BIFs, the following are some example %% recursive functions reimplementing some of the above.   %% Empty string is_empty(<<>>) -> true; is_empty(_) -> false.   %% Replacement: replace(Binary,Value,Replacement) -> replace(Binary,Value,Replacement,<<>>).   replace(<<>>,_,_,Acc) -> Acc; replace(<<Value,Rest/binary>>,Value,Replacement,Acc) -> replace(Rest,Value,Replacement,<< Acc/binary, Replacement >>); replace(<<Keep,Rest/binary>>,Value,Replacement,Acc) -> replace(Rest,Value,Replacement,<< Acc/binary, Keep >>).
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Lua
Lua
  function binner(limits, data) local bins = setmetatable({}, {__index=function() return 0 end}) local n, flr = #limits+1, math.floor for _, x in ipairs(data) do local lo, hi = 1, n while lo < hi do local mid = flr((lo + hi) / 2) if not limits[mid] or x < limits[mid] then hi=mid else lo=mid+1 end end bins[lo] = bins[lo] + 1 end return bins end   function printer(limits, bins) for i = 1, #limits+1 do print(string.format("[%3s,%3s) : %d", limits[i-1] or " -∞", limits[i] or " +∞", bins[i])) end end   print("PART 1:") limits = {23, 37, 43, 53, 67, 83} data = {95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55} bins = binner(limits, data) printer(limits, bins)   print("\nPART 2:") limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} data = {445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749} bins = binner(limits, data) printer(limits, bins)  
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. 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
#Perl
Perl
use strict; use warnings; use feature 'say';   my %cnt; my $total = 0;   while ($_ = <DATA>) { chomp; printf "%4d: %s\n", $total+1, s/(.{10})/$1 /gr; $total += length; $cnt{$_}++ for split // }   say "\nTotal bases: $total"; say "$_: " . ($cnt{$_}//0) for <A C G T>;   __DATA__ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. 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
#Phix
Phix
constant dna = substitute(""" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ""","\n","") sequence acgt = repeat(0,5) for i=1 to length(dna) do acgt[find(dna[i],"ACGT")] += 1 end for acgt[$] = sum(acgt) sequence s = split(trim(join_by(split(join_by(dna,1,10,""),"\n"),1,5," ")),"\n") for i=1 to length(s) do printf(1,"%3d: %s\n",{(i-1)*50+1,s[i]}) end for printf(1,"\nBase counts: A:%d, C:%d, G:%d, T:%d, total:%d\n",acgt)
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#Ada
Ada
with ada.text_io; use ada.text_io; procedure binary is bit : array (0..1) of character := ('0','1');   function bin_image (n : Natural) return string is (if n < 2 then (1 => bit (n)) else bin_image (n / 2) & bit (n mod 2));   test_values : array (1..3) of Natural := (5,50,9000); begin for test of test_values loop put_line ("Output for" & test'img & " is " & bin_image (test)); end loop; end binary;
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Factor
Factor
USING: accessors arrays kernel locals math math.functions math.ranges math.vectors rosettacode.raster.display rosettacode.raster.storage sequences ui.gadgets ; IN: rosettacode.raster.line   :: line-points ( pt1 pt2 -- points ) pt1 first2 :> y0! :> x0! pt2 first2 :> y1! :> x1! y1 y0 - abs x1 x0 - abs > :> steep steep [ y0 x0 y0! x0! y1 x1 y1! x1! ] when x0 x1 > [ x0 x1 x0! x1! y0 y1 y0! y1! ] when x1 x0 - :> deltax y1 y0 - abs :> deltay 0 :> current-error! deltay deltax / abs :> deltaerr 0 :> ystep! y0 :> y! y0 y1 < [ 1 ystep! ] [ -1 ystep! ] if x0 x1 1 <range> [ y steep [ swap ] when 2array current-error deltaerr + current-error! current-error 0.5 >= [ ystep y + y! current-error 1 - current-error! ] when ] { } map-as ;   ! Needs rosettacode.raster.storage for the set-pixel function and to create the image : draw-line ( {R,G,B} pt1 pt2 image -- ) [ line-points ] dip [ set-pixel ] curry with each ;
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Standard_ML
Standard ML
(* For simplicity, we're going to fill black-and-white images. Nothing * fundamental would change if we used more colors. *) datatype color = Black | White (* Represent an image as a 2D mutable array of pixels, since flood-fill * is naturally an imperative algorithm. *) type image = color array array   (* Helper functions to construct images for testing. Map 0 -> White * and 1 -> Black so we can write images concisely as lists. *) fun intToColor 0 = White | intToColor _ = Black   fun listToImage (LL : int list list) : image = Array.tabulate(List.length LL, fn i => Array.tabulate (List.length (hd LL), fn j => intToColor(List.nth(List.nth(LL,i),j))))   (* Is the given pixel within the image ? *) fun inBounds (img : image) ((x,y) : int * int) : bool = x >= 0 andalso y >= 0 andalso y < Array.length img andalso x < Array.length (Array.sub(img, y))   (* Return an option containing the neighbors we should explore next, if any.*) fun neighbors (img : image) (c : color) ((x,y) : int * int) : (int * int) list option = if inBounds img (x,y) andalso Array.sub(Array.sub(img,y),x) <> c then SOME [(x-1,y),(x+1,y),(x,y-1),(x,y+1)] else NONE   (* Update the given pixel of the image. *) fun setPixel (img : image) ((x,y) : int * int) (c : color) : unit = Array.update (Array.sub(img,y),x,c)   (* Recursive fill around the given point using the given color. *) fun fill (img : image) (c : color) ((x,y) : int * int) : unit = case neighbors img c (x,y) of SOME xys => (setPixel img (x,y) c; List.app (fill img c) xys) | NONE => ()   val test = listToImage [[0,0,1,1,0,1,0], [1,0,1,0,1,0,0], [1,0,0,0,0,0,1], [0,1,0,0,0,1,0], [1,0,0,0,0,0,1], [0,0,1,1,1,0,0], [0,1,0,0,0,1,0]]   (* Fill the image with black starting at the center. *) val () = fill test Black (3,3)
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Tcl
Tcl
package require Tcl 8.5 package require Tk package require struct::queue   proc floodFill {img colour point} { set new [colour2rgb $colour] set old [getPixel $img $point] struct::queue Q Q put $point while {[Q size] > 0} { set p [Q get] if {[getPixel $img $p] eq $old} { set w [findBorder $img $p $old west] set e [findBorder $img $p $old east] drawLine $img $new $w $e set q $w while {[x $q] <= [x $e]} { set n [neighbour $q north] if {[getPixel $img $n] eq $old} {Q put $n} set s [neighbour $q south] if {[getPixel $img $s] eq $old} {Q put $s} set q [neighbour $q east] } } } Q destroy }   proc findBorder {img p colour dir} { set lookahead [neighbour $p $dir] while {[getPixel $img $lookahead] eq $colour} { set p $lookahead set lookahead [neighbour $p $dir] } return $p }   proc x p {lindex $p 0} proc y p {lindex $p 1}   proc neighbour {p dir} { lassign $p x y switch -exact -- $dir { west {return [list [incr x -1] $y]} east {return [list [incr x] $y]} north {return [list $x [incr y -1]]} south {return [list $x [incr y]]} } }   proc colour2rgb {color_name} { foreach part [winfo rgb . $color_name] { append colour [format %02x [expr {$part >> 8}]] } return #$colour }   set img [newImage 70 50] fill $img white   drawLine $img blue {0 0} {0 25} drawLine $img blue {0 25} {35 25} drawLine $img blue {35 25} {35 0} drawLine $img blue {35 0} {0 0} floodFill $img yellow {3 3}   drawCircle $img black {35 25} 24 drawCircle $img black {35 25} 10 floodFill $img orange {34 5} floodFill $img red {36 5}   toplevel .flood label .flood.l -image $img pack .flood.l
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nanoquery
Nanoquery
a = true b = false   if a println "a is true" else if b println "b is true" end
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Neko
Neko
/* boolean values */ $print(true, "\n"); $print(false, "\n");   if 0 { $print("literal 0 tests true\n"); } else { $print("literal 0 tests false\n"); }   if 1 { $print("literal 1 tests true\n"); } else { $print("literal 1 tests false\n"); }   if $istrue(0) { $print("$istrue(0) tests true\n"); } else { $print("$istrue(0) tests false\n"); }   if $istrue(1) { $print("$istrue(1) tests true\n"); } else { $print("$istrue(1) tests false\n"); }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nemerle
Nemerle
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]   loop b_ = 0 for bval.length select case bval[b_] when isTrue then say bval[b_] 'is true' when isFalse then say bval[b_] 'is false' otherwise say bval[b_] 'is not boolean' end end b_   method isTrue public static returns boolean return (1 == 1)   method isFalse public static returns boolean return \isTrue  
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Lasso
Lasso
define pointsarray() => { local(points = array) loop(-from=0,-to=32) => { local(heading = loop_count * 11.25) if(loop_count % 3 == 1) => { #heading += 5.62 else(loop_count % 3 == 2) #heading -= 5.62 } #points->insert(#heading) } return #points } define compassShort => array( 'N','Nbe','N-ne','Nebn','Ne','Nebe','E-ne','Ebn', 'E','Ebs','E-se','Sebe','Se','Sebs','S-se','Sbe', 'S','Sbw','S-sw','Swbs','Sw','Swbw','W-sw','Wbs', 'W','Wbn','W-nw','Nwbw','Nw','Nwbn','N-nw','Nbw', 'N') define compassLong(short::string) => { local(o = string) with i in #short->values do => { #o->append(compassLongProcessor(#i)) } return #o } define compassLongProcessor(char::string) => { #char == 'N' ? return #char + 'orth' #char == 'S' ? return #char + 'outh' #char == 'E' ? return #char + 'ast' #char == 'W' ? return #char + 'est' #char == 'b' ? return ' by ' #char == '-' ? return '-' } // test output points as decimals //pointsarray   // test output the array of text values //compassShort   // test output the long names of the text values //with s in compassShort do => {^ compassLong(#s) + '\r' ^}   'angle | box | compass point --------------------------------- ' local(counter = 0) with p in pointsarray do => {^ local(pformatted = #p->asString(-precision=2)) while(#pformatted->size < 6) => { #pformatted->append(' ') } #counter += 1 #counter > 32 ? #counter = 1 #pformatted + ' | ' + (#counter < 10 ? ' ') + #counter + ' | ' + compassLong(compassShort->get(#counter)) + '\r'   ^}
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#ECL
ECL
  BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION BitAND := A & B; BitOR  := A | B; BitXOR := A ^ B; BitNOT := BNOT A; BitSL  := A << B; BitSR  := A >> B; DS  := DATASET([{A,B,'Bitwise AND:',BitAND}, {A,B,'Bitwise OR:',BitOR}, {A,B,'Bitwise XOR',BitXOR}, {A,B,'Bitwise NOT A:',BitNOT}, {A,B,'ShiftLeft A:',BitSL}, {A,B,'ShiftRight A:',BitSR}], {INTEGER AVal,INTEGER BVal,STRING15 valuetype,INTEGER val}); RETURN DS; END;   BitwiseOperations(255,5); //right arithmetic shift, left and right rotate not implemented /* OUTPUT: 255 5 Bitwise AND: 5 255 5 Bitwise OR: 255 255 5 Bitwise XOR 250 255 5 Bitwise NOT A: -256 255 5 ShiftLeft A: 8160 255 5 ShiftRight A: 7   */  
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#Euphoria
Euphoria
-- Some color constants: constant black = #000000, white = #FFFFFF, red = #FF0000, green = #00FF00, blue = #0000FF   -- Create new image filled with some color function new_image(integer width, integer height, atom fill_color) return repeat(repeat(fill_color,height),width) end function   -- Usage example: sequence image image = new_image(800,600,black)   -- Set pixel color: image[400][300] = red   -- Get pixel color atom color color = image[400][300] -- Now color is #FF0000
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Delphi
Delphi
  program BellNumbers;   // For Rosetta Code. // Delphi console application to display the Bell numbers B_0, ..., B_25. // Uses signed 64-bit integers, the largest integer type available in Delphi.   {$APPTYPE CONSOLE}   uses SysUtils; // only for the display   const MAX_INDEX = 25; // maximum index within the limits of int64 var n : integer; // index of Bell number j : integer; // loop variable a : array [0..MAX_INDEX - 1] of int64; // working array to build up B_n   { Subroutine to display that a[0] is the Bell number B_n } procedure Display(); begin WriteLn( SysUtils.Format( 'B_%-2d = %d', [n, a[0]])); end;   (* Main program *) begin n := 0; a[0] := 1; Display(); // some programmers would prefer Display; while (n < MAX_INDEX) do begin // and give begin a line to itself a[n] := a[0]; for j := n downto 1 do inc( a[j - 1], a[j]); inc(n); Display(); end; end.  
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Common_Lisp
Common Lisp
(defun calculate-distribution (numbers) "Return the frequency distribution of the most significant nonzero digits in the given list of numbers. The first element of the list is the frequency for digit 1, the second for digit 2, and so on."   (defun nonzero-digit-p (c) "Check whether the character is a nonzero digit" (and (digit-char-p c) (char/= c #\0)))   (defun first-digit (n) "Return the most significant nonzero digit of the number or NIL if there is none." (let* ((s (write-to-string n)) (c (find-if #'nonzero-digit-p s))) (when c (digit-char-p c))))   (let ((tally (make-array 9 :element-type 'integer :initial-element 0))) (loop for n in numbers for digit = (first-digit n) when digit do (incf (aref tally (1- digit)))) (loop with total = (length numbers) for digit-count across tally collect (/ digit-count total))))   (defun calculate-benford-distribution () "Return the frequency distribution according to Benford's law. The first element of the list is the probability for digit 1, the second element the probability for digit 2, and so on." (loop for i from 1 to 9 collect (log (1+ (/ i)) 10)))   (defun benford (numbers) "Print a table of the actual and expected distributions for the given list of numbers." (let ((actual-distribution (calculate-distribution numbers)) (expected-distribution (calculate-benford-distribution))) (write-line "digit actual expected") (format T "~:{~3D~9,3F~8,3F~%~}" (map 'list #'list '(1 2 3 4 5 6 7 8 9) actual-distribution expected-distribution))))
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#Clojure
Clojure
    ns test-project-intellij.core (:gen-class))   (defn a-t [n] " Used Akiyama-Tanigawa algorithm with a single loop rather than double nested loop " " Clojure does fractional arithmetic automatically so that part is easy " (loop [m 0 j m A (vec (map #(/ 1 %) (range 1 (+ n 2))))] ; Prefil A(m) with 1/(m+1), for m = 1 to n (cond ; Three way conditional allows single loop (>= j 1) (recur m (dec j) (assoc A (dec j) (* j (- (nth A (dec j)) (nth A j))))) ; A[j-1] ← j×(A[j-1] - A[j]) ; (< m n) (recur (inc m) (inc m) A) ; increment m, reset j = m  :else (nth A 0))))   (defn format-ans [ans] " Formats answer so that '/' is aligned for all answers " (if (= ans 1) (format "%50d / %8d" 1 1) (format "%50d / %8d" (numerator ans) (denominator ans))))   ;; Generate a set of results for [0 1 2 4 ... 60] (doseq [q (flatten [0 1 (range 2 62 2)])  :let [ans (a-t q)]] (println q ":" (format-ans ans)))    
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#ALGOL_W
ALGOL W
begin % binary search %  % recursive binary search, left most insertion point % integer procedure binarySearchLR ( integer array A ( * )  ; integer value find, Low, high ) ; if high < low then low else begin integer mid; mid := ( low + high ) div 2; if A( mid ) >= find then binarySearchLR( A, find, low, mid - 1 ) else binarySearchLR( A, find, mid + 1, high ) end binarySearchR ;  % iteratve binary search leftmost insertion point % integer procedure binarySearchLI ( integer array A ( * )  ; integer value find, lowInit, highInit ) ; begin integer low, high; low  := lowInit; high := highInit; while low <= high do begin integer mid; mid := ( low + high ) div 2; if A( mid ) >= find then high := mid - 1 else low  := mid + 1 end while_low_le_high ; low end binarySearchLI ;  % tests % begin integer array t ( 1 :: 10 ); integer tPos; tPos := 1; for tValue := 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 do begin t( tPos ) := tValue; tPos  := tPOs + 1 end for_tValue ; for s := 0 step 8 until 24 do begin integer pos; pos := binarySearchLR( t, s, 1, 10 ); if t( pos ) = s then write( I_W := 3, S_W := 0, "recursive search finds ", s, " at ", pos ) else write( I_W := 3, S_W := 0, "recursive search suggests insert ", s, " at ", pos )  ; pos := binarySearchLI( t, s, 1, 10 ); if t( pos ) = s then write( I_W := 3, S_W := 0, "iterative search finds ", s, " at ", pos ) else write( I_W := 3, S_W := 0, "iterative search suggests insert ", s, " at ", pos ) end for_s end end.
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <limits.h>   #define DEBUG   void best_shuffle(const char* txt, char* result) { const size_t len = strlen(txt); if (len == 0) return;   #ifdef DEBUG // txt and result must have the same length assert(len == strlen(result)); #endif   // how many of each character? size_t counts[UCHAR_MAX]; memset(counts, '\0', UCHAR_MAX * sizeof(int)); size_t fmax = 0; for (size_t i = 0; i < len; i++) { counts[(unsigned char)txt[i]]++; const size_t fnew = counts[(unsigned char)txt[i]]; if (fmax < fnew) fmax = fnew; } assert(fmax > 0 && fmax <= len);   // all character positions, grouped by character size_t *ndx1 = malloc(len * sizeof(size_t)); if (ndx1 == NULL) exit(EXIT_FAILURE); for (size_t ch = 0, i = 0; ch < UCHAR_MAX; ch++) if (counts[ch]) for (size_t j = 0; j < len; j++) if (ch == (unsigned char)txt[j]) { ndx1[i] = j; i++; }   // regroup them for cycles size_t *ndx2 = malloc(len * sizeof(size_t)); if (ndx2 == NULL) exit(EXIT_FAILURE); for (size_t i = 0, n = 0, m = 0; i < len; i++) { ndx2[i] = ndx1[n]; n += fmax; if (n >= len) { m++; n = m; } }   // how long can our cyclic groups be? const size_t grp = 1 + (len - 1) / fmax; assert(grp > 0 && grp <= len);   // how many of them are full length? const size_t lng = 1 + (len - 1) % fmax; assert(lng > 0 && lng <= len);   // rotate each group for (size_t i = 0, j = 0; i < fmax; i++) { const size_t first = ndx2[j]; const size_t glen = grp - (i < lng ? 0 : 1); for (size_t k = 1; k < glen; k++) ndx1[j + k - 1] = ndx2[j + k]; ndx1[j + glen - 1] = first; j += glen; }   // result is original permuted according to our cyclic groups result[len] = '\0'; for (size_t i = 0; i < len; i++) result[ndx2[i]] = txt[ndx1[i]];   free(ndx1); free(ndx2); }   void display(const char* txt1, const char* txt2) { const size_t len = strlen(txt1); assert(len == strlen(txt2)); int score = 0; for (size_t i = 0; i < len; i++) if (txt1[i] == txt2[i]) score++; (void)printf("%s, %s, (%u)\n", txt1, txt2, score); }   int main() { const char* data[] = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "aabbbbaa", "", "xxxxx"}; const size_t data_len = sizeof(data) / sizeof(data[0]); for (size_t i = 0; i < data_len; i++) { const size_t shuf_len = strlen(data[i]) + 1; char shuf[shuf_len];   #ifdef DEBUG memset(shuf, 0xFF, sizeof shuf); shuf[shuf_len - 1] = '\0'; #endif   best_shuffle(data[i], shuf); display(data[i], shuf); }   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Factor
Factor
"Hello, byte-array!" utf8 encode .
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Forth
Forth
\ Rosetta Code Binary Strings Demo in Forth \ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html   \ String words created in this code: \ STR< STR> STR= COMPARESTR SUBSTR STRPAD CLEARSTR \ ="" =" STRING: MAXLEN REPLACE-CHAR COPYSTR WRITESTR \ ," APPEND-CHAR STRING, PLACE CONCAT APPEND C+! ENDSTR \ COUNT STRLEN   : STRLEN ( addr -- length) c@ ; \ alias the "character fetch" operator   : COUNT ( addr -- addr+1 length) \ Standard word. Shown for explanation dup strlen swap 1+ swap ; \ returns the address+1 and the length byte on the stack   : ENDSTR ( str -- addr) \ calculate the address at the end of a string COUNT + ;   : C+! ( n addr -- ) \ primitive: increment a byte at addr by n DUP C@ ROT + SWAP C! ;   : APPEND ( addr1 length addr2 -- ) \ Append addr1 length to addr2 2dup 2>r endstr swap move 2r> c+! ;   : CONCAT ( string1 string2 -- ) \ concatenate counted string1 to counted string2 >r COUNT R> APPEND ;   : PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string 2dup 2>r char+ swap move 2r> c! ;   : STRING, ( addr len -- ) \ compile a string at the next available memory (called 'HERE') here over char+ allot place ;   : APPEND-CHAR ( char string -- ) \ append char to string dup >r count dup 1+ r> c! + c! ;   : ," [CHAR] " PARSE STRING, ; \ Parse input stream until '"' and compile into memory     : WRITESTR ( string -- ) \ output a counted string with a carriage return count type CR ;   : COPYSTR ( string1 string3 -- ) \ String cloning and copying COPYSTR >r count r> PLACE ;   : REPLACE-CHAR ( char1 char2 string -- ) \ replace all char2 with char1 in string count \ get string's address and length BOUNDS \ calc start and end addr of string for do-loop DO \ do a loop from start address to end address I C@ OVER = \ fetch the char at loop index compare to CHAR2 IF OVER I C! \ if its equal, store CHAR1 into the index address THEN LOOP 2drop ; \ drop the chars off the stack     256 constant maxlen \ max size of byte counted string in this example   : string: CREATE maxlen ALLOT ; \ simple string variable constructor     : =" ( string -- ) \ String variable assignment operator (compile time only) [char] " PARSE ROT PLACE ;   : ="" ( string -- ) 0 swap c! ; \ empty a string, set count to zero     : clearstr ( string -- ) \ erase a string variables contents, fill with 0 maxlen erase ;     string: strpad \ general purpose storage buffer   : substr ( string1 start length -- strpad) \ Extract a substring of string and return an output string >r >r \ push start,length count \ compute addr,len r> 1- /string \ pop start, subtract 1, cut string drop r> \ drop existing length, pop new length strpad place \ place new stack string in strpad strpad ; \ return address of strpad   \ COMPARE takes the 4 inputs from the stack (addr1 len1 addr2 len2 ) \ and returns a flag for equal (0) , less-than (1) or greater-than (-1) on the stack    : comparestr ( string1 string2 -- flag) \ adapt for use with counted strings count rot count compare ;   \ now it's simple to make new operators  : STR= ( string1 string2 -- flag) comparestr 0= ;    : STR> ( string1 string2 -- flag) comparestr -1 = ;    : STR< ( string1 string2 -- flag) comparestr 1 = ;    
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
limits = {23, 37, 43, 53, 67, 83}; data = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; limits = {{-\[Infinity]}~Join~limits~Join~{\[Infinity]}}; BinCounts[data, limits] MapThread[{#2, #1} &, {%, Partition[First[limits], 2, 1]}] // Grid   limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; data = {445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; limits = {{-\[Infinity]}~Join~limits~Join~{\[Infinity]}}; BinCounts[data, limits] MapThread[{#2, #1} &, {%, Partition[First[limits], 2, 1]}] // Grid
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Nim
Nim
import algorithm, strformat   func binIt(limits, data: openArray[int]): seq[Natural] = result.setLen(limits.len + 1) for d in data: inc result[limits.upperBound(d)]   proc binPrint(limits: openArray[int]; bins: seq[Natural]) = echo &" < {limits[0]:3} := {bins[0]:3}" for i in 1..limits.high: echo &">= {limits[i-1]:3} .. < {limits[i]:3} := {bins[i]:3}" echo &">= {limits[^1]:3}  := {bins[^1]:3}"     when isMainModule:   echo "Example 1:" const Limits1 = [23, 37, 43, 53, 67, 83] Data1 = [95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55] let bins1 = binIt(Limits1, Data1) binPrint(Limits1, bins1)   echo "" echo "Example 2:" const Limits2 = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] Data2 = [445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749] let bins2 = binIt(Limits2, Data2) binPrint(Limits2, bins2)
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Picat
Picat
main => dna(DNA, ChunkSize), Count = 0, println("Sequence:"), Map = new_map(['A'=0,'C'=0,'G'=0,'T'=0]), foreach(Chunk in DNA.chunks_of(ChunkSize)) printf("%4d: %s\n", Count, Chunk), Count := Count + Chunk.len, foreach(C in Chunk) Map.put(C,Map.get(C)+1) end end, println("\nBase count:"), foreach(C in "ACGT") printf("%5c: %3d\n", C, Map.get(C)) end, printf("Total: %d\n", Count), nl.   dna(DNA,ChunkSize) => DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT".delete_all('\n'), ChunkSize = 50.
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(let (S (chop "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" ) R ) (for I S (accu 'R I 1)) (for I R (println I)) (println 'Total: (sum cdr R)) )
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#Aime
Aime
o_xinteger(2, 0); o_byte('\n'); o_xinteger(2, 5); o_byte('\n'); o_xinteger(2, 50); o_byte('\n'); o_form("/x2/\n", 9000);
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Bresenham") ' Set form caption FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 200, 235) CENTER(ME) SHOW(ME)   BEGIN EVENTS SELECT CASE CBMSG CASE WM_LBUTTONDOWN: Rhombus() ' Draw CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up END SELECT END EVENTS   SUB Rhombus() Bresenham(50, 100, 100, 190)(100, 190, 150, 100)(150, 100, 100, 10)(100, 10, 50, 100)   SUB Bresenham(x0, y0, x1, y1) DIM dx = ABS(x0 - x1), sx = SGN(x0 - x1) DIM dy = ABS(y0 - y1), sy = SGN(y0 - y1) DIM tmp, er = IIF(dx > dy, dx, -dy) / 2   WHILE NOT (x0 = x1 ANDALSO y0 = y1) PSET(FBSL.GETDC, x0, y0, &HFF) ' Red: Windows stores colors in BGR order tmp = er IF tmp > -dx THEN: er = er - dy: x0 = x0 + sx: END IF IF tmp < +dy THEN: er = er + dx: y0 = y0 + sy: END IF WEND END SUB END SUB
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window import "input" for Keyboard   class Bitmap { construct new(name, size) { Window.title = name Window.resize(size, size) Canvas.resize(size, size) size = size / 2 _bmp = ImageData.create(name, size, size) _size = size _flooded = false }   init() { var s = _size var hs = s / 2 var qs = s / 4 fill(0, 0, s, s, Color.yellow) fill(qs, qs, 3 * qs, 3 * qs, Color.red) fill(qs * 1.5, qs * 1.5, qs * 2.5, qs * 2.5, Color.white) _bmp.draw(hs, hs) }   fill(s, t, w, h, col) { for (x in s...w) { for (y in t...h) pset(x, y, col) } }   flood(x, y, repl) { var target = pget(x, y) var ff // recursive closure ff = Fn.new { |x, y| if (x >= 0 && x < _bmp.width && y >= 0 && y < _bmp.height) { var p = pget(x, y) if (p.r == target.r && p.g == target.g && p.b == target.b) { pset(x, y, repl) ff.call(x-1, y) ff.call(x+1, y) ff.call(x, y-1) ff.call(x, y+1) } } } ff.call(x, y) }   pset(x, y, col) { _bmp.pset(x, y, col) }   pget(x, y) { _bmp.pget(x, y) }   update() { var hs = _size / 2 var qs = _size / 4 if (!_flooded && Keyboard.isKeyDown("up")) { flood(qs, qs, Color.blue) _bmp.draw(hs, hs) _flooded = true } else if (_flooded && Keyboard.isKeyDown("down")) { flood(qs, qs, Color.red) _bmp.draw(hs, hs) _flooded = false } }   draw(alpha) {} }   var Game = Bitmap.new("Bitmap - flood fill", 600)
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]   loop b_ = 0 for bval.length select case bval[b_] when isTrue then say bval[b_] 'is true' when isFalse then say bval[b_] 'is false' otherwise say bval[b_] 'is not boolean' end end b_   method isTrue public static returns boolean return (1 == 1)   method isFalse public static returns boolean return \isTrue  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nim
Nim
if true: echo "yes" if false: echo "no"   # Other objects never represent true or false: if 2: echo "compile error"
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Liberty_BASIC
Liberty BASIC
dim point$( 32)   for i =1 to 32 read d$: point$( i) =d$ next i   for i = 0 to 32 heading = i *11.25 if ( i mod 3) =1 then heading = heading +5.62 else if ( i mod 3) =2 then heading = heading -5.62 end if ind = i mod 32 +1 print ind, compasspoint$( heading), heading next i   end   function compasspoint$( h) x = h /11.25 +1.5 if (x >=33.0) then x =x -32.0 compasspoint$ = point$( int( x)) end function   data "North ", "North by east ", "North-northeast " data "Northeast by north", "Northeast ", "Northeast by east ", "East-northeast " data "East by north ", "East ", "East by south ", "East-southeast " data "Southeast by east ", "Southeast ", "Southeast by south", "South-southeast " data "South by east ", "South ", "South by west ", "South-southwest " data "Southwest by south", "Southwest ", "Southwest by west ", "West-southwest " data "West by south ", "West ", "West by north ", "West-northwest " data "Northwest by west ", "Northwest ", "Northwest by north", "North-northwest " data "North by west
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#Elena
Elena
import extensions;   extension testOp { bitwiseTest(y) { console.printLine(self," and ",y," = ",self.and(y)); console.printLine(self," or ",y," = ",self.or(y)); console.printLine(self," xor ",y," = ",self.xor(y)); console.printLine("not ",self," = ",self.Inverted); console.printLine(self," shr ",y," = ",self.shiftRight(y)); console.printLine(self," shl ",y," = ",self.shiftLeft(y)); } }   public program() { console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer())) }
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#F.23
F#
  //pure functional version ... changing a pixel color provides a new Bitmap type Color = {red: byte; green: byte; blue: byte} type Point = {x:uint32; y:uint32} type Bitmap = {color: Color array; maxX: uint32; maxY: uint32}   let colorBlack = {red = (byte) 0; green = (byte) 0; blue = (byte) 0} let emptyBitmap = {color = Array.empty; maxX = (uint32) 0; maxY = (uint32) 0} let bitmap (width: uint32) (height: uint32) = match width, height with | 0u,0u | 0u,_ | _, 0u -> emptyBitmap | _,_ -> {color = Array.create ((int) (width * height)) colorBlack; maxX = width; maxY = height} let getPixel point bitmap = match bitmap.color with | c when c |> Array.isEmpty -> None | c when (uint32) c.Length <= (point.y * bitmap.maxY + point.x) -> None | c -> Some c.[(int) (point.y * bitmap.maxY + point.x)] let setPixel point color bitmap = {bitmap with color = bitmap.color |> Array.mapi (function | i when i = (int) (point.y * bitmap.maxY + point.x) -> (fun _ -> color) | _ -> id)} let fill color bitmap = {bitmap with color = bitmap.color |> Array.map (fun _ ->color)}  
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Elixir
Elixir
  defmodule Bell do def triangle(), do: Stream.iterate([1], fn l -> bell_row l, [List.last l] end) def numbers(), do: triangle() |> Stream.map(&List.first/1)   defp bell_row([], r), do: Enum.reverse r defp bell_row([a|a_s], r = [r0|_]), do: bell_row(a_s, [a + r0|r]) end   :io.format "The first 15 bell numbers are ~p~n~n", [Bell.numbers() |> Enum.take(15)]   IO.puts "The 50th Bell number is #{Bell.numbers() |> Enum.take(50) |> List.last}" IO.puts ""   IO.puts "THe first 10 rows of Bell's triangle:" IO.inspect(Bell.triangle() |> Enum.take(10))  
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#F.23
F#
  // Generate bell triangle. Nigel Galloway: July 6th., 2019 let bell=Seq.unfold(fun g->Some(g,List.scan(+) (List.last g) g))[1I]  
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Crystal
Crystal
require "big"   EXPECTED = (1..9).map{ |d| Math.log10(1 + 1.0 / d) }   def fib(n) a, b = 0.to_big_i, 1.to_big_i (0...n).map { ret, a, b = a, b, a + b; ret } end   # powers of 3 as a test sequence def power_of_threes(n) (0...n).map { |k| 3.to_big_i ** k } end   def heads(s) s.map { |a| a.to_s[0].to_i } end   def show_dist(title, s) s = heads(s) c = Array.new(10, 0) s.each{ |x| c[x] += 1 } siz = s.size res = (1..9).map{ |d| c[d] / siz } puts "\n  %s Benfords deviation" % title res.zip(EXPECTED).each_with_index(1) do |(r, e), i| puts "%2d: %5.1f%%  %5.1f%%  %5.1f%%" % [i, r*100, e*100, (r - e).abs*100] end end   def random(n) (0...n).map { |i| rand(1..n) } end   show_dist("fibbed", fib(1000)) show_dist("threes", power_of_threes(1000))   # just to show that not all kind-of-random sets behave like that show_dist("random", random(10000))
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#Common_Lisp
Common Lisp
(defun bernouilli (n) (loop with a = (make-array (list (1+ n))) for m from 0 to n do (setf (aref a m) (/ 1 (+ m 1))) (loop for j from m downto 1 do (setf (aref a (- j 1)) (* j (- (aref a j) (aref a (- j 1)))))) finally (return (aref a 0))))   ;;Print outputs to stdout:   (loop for n from 0 to 60 do (let ((b (bernouilli n))) (when (not (zerop b)) (format t "~a: ~a~%" n b))))     ;;For the "extra credit" challenge, we need to align the slashes.   (let (results) ;;collect the results (loop for n from 0 to 60 do (let ((b (bernouilli n))) (when (not (zerop b)) (push (cons b n) results)))) ;;parse the numerators into strings; save the greatest length in max-length (let ((max-length (apply #'max (mapcar (lambda (r) (length (format nil "~a" (numerator r)))) (mapcar #'car results))))) ;;Print the numbers with using the fixed-width formatter: ~Nd, where N is ;;the number of leading spaces. We can't just pass in the width variable ;;but we can splice together a formatting string that includes it.   ;;We also can't use the fixed-width formatter on a ratio, so we have to split ;;the ratio and splice it back together like idiots. (loop for n in (mapcar #'cdr (reverse results)) for r in (mapcar #'car (reverse results)) do (format t (concatenate 'string "B(~2d): ~" (format nil "~a" max-length) "d/~a~%") n (numerator r) (denominator r)))))
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#APL
APL
binsrch←{ ⎕IO(⍺{ ⍝ first lower bound is start of array ⍵<⍺:⍬ ⍝ if high < low, we didn't find it mid←⌊(⍺+⍵)÷2 ⍝ calculate mid point ⍺⍺[mid]>⍵⍵:⍺∇mid-1 ⍝ if too high, search from ⍺ to mid-1 ⍺⍺[mid]<⍵⍵:(mid+1)∇⍵ ⍝ if too low, search from mid+1 to ⍵ mid ⍝ otherwise, we did find it }⍵)⎕IO+(≢⍺)-1 ⍝ first higher bound is top of array }  
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.23
C#
ShuffledString[] array = {"cat", "dog", "mouse"};
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <algorithm>   using namespace std;   template <class S> class BestShuffle { public: BestShuffle() : rd(), g(rd()) {}   S operator()(const S& s1) { S s2 = s1; shuffle(s2.begin(), s2.end(), g); for (unsigned i = 0; i < s2.length(); i++) if (s2[i] == s1[i]) for (unsigned j = 0; j < s2.length(); j++) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { swap(s2[i], s2[j]); break; } ostringstream os; os << s1 << endl << s2 << " [" << count(s2, s1) << ']'; return os.str(); }   private: static int count(const S& s1, const S& s2) { auto count = 0; for (unsigned i = 0; i < s1.length(); i++) if (s1[i] == s2[i]) count++; return count; }   random_device rd; mt19937 g; };   int main(int argc, char* arguments[]) { BestShuffle<basic_string<char>> bs; for (auto i = 1; i < argc; i++) cout << bs(basic_string<char>(arguments[i])) << endl; return 0; }
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#FreeBASIC
FreeBASIC
  Dim As String cad, cad2 'creación de cadenas cad = "¡Hola Mundo!"   'destrucción de cadenas: no es necesario debido a la recolección de basura cad = ""   'clonación/copia de cadena cad2 = cad   'comparación de cadenas If cad = cad2 Then Print "Las cadenas son iguales"   'comprobar si está vacío If cad = "" Then Print "Cadena vac¡a"   'agregar un byte cad += Chr(33)   'extraer una subcadena cad2 = Mid(cad, 1, 5)   'reemplazar bytes cad2 = "­Hola mundo!" For i As Integer = 1 To Len(cad2) If Mid(cad2,i,1) = "l" Then cad2 = Left(cad2,i-1) + "L" + Mid(cad2,i+1) End If Next Print cad2   'unir cadenas cad = "Hasta " + "pronto " + "de momento."   'imprimir caracteres 2 a 4 de una cadena (una subcadena) For i As Integer = 2 To 4 Print Chr(cad[i]) Next i Sleep  
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   NSArray<NSNumber *> *bins(NSArray<NSNumber *> *limits, NSArray<NSNumber *> *data) { NSMutableArray<NSNumber *> *result = [[NSMutableArray alloc] initWithCapacity:[limits count] + 1]; for (NSInteger i = 0; i <= [limits count]; i++) { [result addObject:@0]; } for (NSNumber *n in data) { NSUInteger i = [limits indexOfObject:n inSortedRange:NSMakeRange(0, [limits count]) options:NSBinarySearchingInsertionIndex|NSBinarySearchingLastEqual usingComparator:^(NSNumber *x, NSNumber *y){ return [x compare: y]; }]; result[i] = @(result[i].integerValue + 1); } return result; }   void printBins(NSArray<NSNumber *> *limits, NSArray<NSNumber *> *bins) { NSUInteger n = [limits count]; if (n == 0) return; NSCAssert(n + 1 == [bins count], @"Wrong size of bins"); NSLog(@" < %3@: %2@", limits[0], bins[0]); for (NSInteger i = 1; i < n; i++) { NSLog(@">= %3@ and < %3@: %2@", limits[i-1], limits[i], bins[i]); } NSLog(@">= %3@  : %2@", limits[n-1], bins[n]); }   int main(void) { @autoreleasepool { NSArray<NSNumber *> *limits = @[@23, @37, @43, @53, @67, @83]; NSArray<NSNumber *> *data = @[ @95, @21, @94, @12, @99, @4, @70, @75, @83, @93, @52, @80, @57, @5, @53, @86, @65, @17, @92, @83, @71, @61, @54, @58, @47, @16, @8, @9, @32, @84, @7, @87, @46, @19, @30, @37, @96, @6, @98, @40, @79, @97, @45, @64, @60, @29, @49, @36, @43, @55];   NSLog(@"Example 1:"); printBins(limits, bins(limits, data));   limits = @[@14, @18, @249, @312, @389, @392, @513, @591, @634, @720]; data = @[ @445, @814, @519, @697, @700, @130, @255, @889, @481, @122, @932, @77, @323, @525, @570, @219, @367, @523, @442, @933, @416, @589, @930, @373, @202, @253, @775, @47, @731, @685, @293, @126, @133, @450, @545, @100, @741, @583, @763, @306, @655, @267, @248, @477, @549, @238, @62, @678, @98, @534, @622, @907, @406, @714, @184, @391, @913, @42, @560, @247, @346, @860, @56, @138, @546, @38, @985, @948, @58, @213, @799, @319, @390, @634, @458, @945, @733, @507, @916, @123, @345, @110, @720, @917, @313, @845, @426, @9, @457, @628, @410, @723, @354, @895, @881, @953, @677, @137, @397, @97, @854, @740, @83, @216, @421, @94, @517, @479, @292, @963, @376, @981, @480, @39, @257, @272, @157, @5, @316, @395, @787, @942, @456, @242, @759, @898, @576, @67, @298, @425, @894, @435, @831, @241, @989, @614, @987, @770, @384, @692, @698, @765, @331, @487, @251, @600, @879, @342, @982, @527, @736, @795, @585, @40, @54, @901, @408, @359, @577, @237, @605, @847, @353, @968, @832, @205, @838, @427, @876, @959, @686, @646, @835, @127, @621, @892, @443, @198, @988, @791, @466, @23, @707, @467, @33, @670, @921, @180, @991, @396, @160, @436, @717, @918, @8, @374, @101, @684, @727, @749];   NSLog(@""); NSLog(@"Example 2:"); printBins(limits, bins(limits, data)); } return 0; }
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PureBasic
PureBasic
dna$ = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   NewMap basecount.i()   If OpenConsole("") For i = 1 To Len(dna$) If (i % 50) = 1 Print(~"\n" + RSet(Str(i - 1), 5) + " : ") EndIf t$ = Mid(dna$, i, 1) basecount(t$) + 1 Print(t$) Next   PrintN(~"\n\n" + Space(2) + "Base count") PrintN(Space(2) + ~"---- -----") ForEach basecount() PrintN(RSet(MapKey(basecount()), 5) + " : " + RSet(Str(basecount()), 5)) sigma + basecount() Next PrintN(~"\n" + "Total = " + RSet(Str(sigma), 5)) Input() EndIf
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   printf(( $g" => "2r3d l$, 5, BIN 5, $g" => "2r6d l$, 50, BIN 50, $g" => "2r14d l$, 9000, BIN 9000 ));   # or coerce to an array of BOOL # print(( 5, " => ", []BOOL(BIN 5)[bits width-3+1:], new line, 50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line, 9000, " => ", []BOOL(BIN 9000)[bits width-14+1:], new line ))
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Forth
Forth
defer steep \ noop or swap defer ystep \ 1+ or 1-   : line ( x0 y0 x1 y1 color bmp -- ) { color bmp } rot swap ( x0 x1 y0 y1 ) 2dup - abs >r 2over - abs r> < if ['] swap \ swap use of x and y else 2swap ['] noop then is steep ( y0 y1 x0 x1 ) 2dup > if swap 2swap swap \ ensure x1 > x0 else 2swap then ( x0 x1 y0 y1 ) 2dup > if ['] 1- else ['] 1+ then is ystep over - abs { y deltay } swap 2dup - dup { deltax } 2/ rot 1+ rot ( error x1+1 x0 ) do color i y steep bmp b! deltay - dup 0< if y ystep to y deltax + then loop drop ;   5 5 bitmap value test 0 test bfill 1 0 4 1 red test line 4 1 3 4 red test line 3 4 0 3 red test line 0 3 1 0 red test line test bshow cr ** * ** * * ** * ** ok
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#XPL0
XPL0
include c:\cxpl\codes;   proc Flood(X, Y, C, C0); \Fill an area of color C0 with color C int X, Y, \seed coordinate (where to start) C, C0; \color to fill with and color to replace def S=8000; \size of queue (must be an even number) int Q(S), \queue (FIFO) F, E; \fill and empty indexes   proc EnQ(X, Y); \Enqueue coordinate int X, Y; [Q(F):= X; F:= F+1; Q(F):= Y; F:= F+1; if F >= S then F:= 0; ]; \EnQ   proc DeQ; \Dequeue coordinate [X:= Q(E); E:= E+1; Y:= Q(E); E:= E+1; if E >= S then E:= 0; ]; \DeQ   [F:= 0; E:= 0; EnQ(X, Y); while E # F do [DeQ; if ReadPix(X, Y) = C0 then [Point(X, Y, C); EnQ(X+1, Y); \enqueue adjacent pixels EnQ(X-1, Y); EnQ(X, Y+1); EnQ(X, Y-1); ]; ]; ]; \Flood   def Size = 30.0; int X, Y; real Ang, Dist; [SetVid($101); \set 640x480 graphics with 256 colors   Ang:= 0.0; \draw some flower petals repeat Dist:= Size*(Cos(Ang*3.0) - 1.0); X:= fix(Dist*Cos(Ang)); Y:= fix(Dist*Sin(Ang)); Point(X+320, 240-Y, $F); Ang:= Ang + 0.001; \draw dots close together to prevent leaks until Ang >= 2.0*3.14159;   Flood(330, 240, $2A, 0); \color the petals Flood(310, 230, $2C, 0); Flood(310, 250, $2E, 0);   if ChIn(1) then []; \wait for keystroke SetVid(3); \restore normal text mode ]
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#zkl
zkl
fcn flood(pixmap, x,y, repl){ // slow! targ,h,w:=pixmap[x,y], pixmap.h,pixmap.w; stack:=List(T(x,y)); while(stack){ x,y:=stack.pop(); if((0<=y<h) and (0<=x<w)){ p:=pixmap[x,y]; if(p==targ){ pixmap[x,y]=repl; stack.append( T(x-1,y), T(x+1,y), T(x, y-1), T(x, y+1) ); } } } }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oberon-2
Oberon-2
  VAR a,b,c: BOOLEAN; ... a := TRUE; b := FALSE; c := 1 > 2;  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Objeck
Objeck
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Object_Pascal
Object Pascal
type bool = false | true
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#LLVM
LLVM
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring.   ; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps   ;--- The declarations for the external C functions declare i32 @printf(i8*, ...)   $"COMPASS_STR" = comdat any $"OUTPUT_STR" = comdat any   @main.degrees = private unnamed_addr constant [33 x double] [double 0.000000e+00, double 1.687000e+01, double 1.688000e+01, double 3.375000e+01, double 5.062000e+01, double 5.063000e+01, double 6.750000e+01, double 8.437000e+01, double 0x40551851EB851EB8, double 1.012500e+02, double 1.181200e+02, double 1.181300e+02, double 1.350000e+02, double 1.518700e+02, double 1.518800e+02, double 1.687500e+02, double 1.856200e+02, double 1.856300e+02, double 2.025000e+02, double 2.193700e+02, double 2.193800e+02, double 2.362500e+02, double 2.531200e+02, double 2.531300e+02, double 2.700000e+02, double 2.868700e+02, double 2.868800e+02, double 3.037500e+02, double 3.206200e+02, double 3.206300e+02, double 3.375000e+02, double 3.543700e+02, double 3.543800e+02], align 16 @"COMPASS_STR" = linkonce_odr unnamed_addr constant [727 x i8] c"North North by east North-northeast Northeast by north Northeast Northeast by east East-northeast East by north East East by south East-southeast Southeast by east Southeast Southeast by south South-southeast South by east South South by west South-southwest Southwest by south Southwest Southwest by west West-southwest West by south West West by north West-northwest Northwest by west Northwest Northwest by north North-northwest North by west North \00", comdat, align 1 @"OUTPUT_STR" = linkonce_odr unnamed_addr constant [19 x i8] c"%2d  %.22s  %6.2f\0A\00", comdat, align 1   ; Function Attrs: noinline nounwind optnone uwtable define i32 @main() #0 { %1 = alloca i32, align 4 ;-- allocate i %2 = alloca i32, align 4 ;-- allocate j %3 = alloca [33 x double], align 16 ;-- allocate degrees %4 = alloca i8*, align 8 ;-- allocate names %5 = bitcast [33 x double]* %3 to i8* call void @llvm.memcpy.p0i8.p0i8.i64(i8* %5, i8* bitcast ([33 x double]* @main.degrees to i8*), i64 264, i32 16, i1 false) store i8* getelementptr inbounds ([727 x i8], [727 x i8]* @"COMPASS_STR", i32 0, i32 0), i8** %4, align 8 store i32 0, i32* %1, align 4 ;-- i = 0 br label %loop   loop: %6 = load i32, i32* %1, align 4 ;-- load i %7 = icmp slt i32 %6, 33 ;-- i < 33 br i1 %7, label %loop_body, label %exit   loop_body: %8 = load i32, i32* %1, align 4 ;-- load i %9 = sext i32 %8 to i64 ;-- sign extend i %10 = getelementptr inbounds [33 x double], [33 x double]* %3, i64 0, i64 %9 ;-- calculate index of degrees[i] %11 = load double, double* %10, align 8 ;-- load degrees[i] %12 = fmul double %11, 3.200000e+01 ;-- degrees[i] * 32 %13 = fdiv double %12, 3.600000e+02 ;-- degrees[i] * 32 / 360.0 %14 = fadd double 5.000000e-01, %13 ;-- 0.5 + degrees[i] * 32 / 360.0 %15 = fptosi double %14 to i32 ;-- convert floating point to integer store i32 %15, i32* %2, align 4 ;-- write result to j   %16 = load i8*, i8** %4, align 8 ;-- load names %17 = load i32, i32* %2, align 4 ;-- load j %18 = srem i32 %17, 32 ;-- j % 32 %19 = mul nsw i32 %18, 22 ;-- (j % 32) * 22 %20 = sext i32 %19 to i64 ;-- sign extend the result %21 = getelementptr inbounds i8, i8* %16, i64 %20 ;-- load names at the calculated offset %22 = load i32, i32* %2, align 4 ;-- load j %23 = srem i32 %22, 32 ;-- j % 32 %24 = add nsw i32 %23, 1 ;-- (j % 32) + 1 %25 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([19 x i8], [19 x i8]* @"OUTPUT_STR", i32 0, i32 0), i32 %24, i8* %21, double %11)   %26 = load i32, i32* %1, align 4 ;-- load i %27 = add nsw i32 %26, 1 ;-- increment i store i32 %27, i32* %1, align 4 ;-- store i br label %loop   exit: ret i32 0 }   ; Function Attrs: argmemonly nounwind declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture writeonly, i8* nocapture readonly, i64, i32, i1) #1   attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #1 = { argmemonly nounwind }
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#Elixir
Elixir
defmodule Bitwise_operation do use Bitwise   def test(a \\ 255, b \\ 170, c \\ 2) do IO.puts "Bitwise function:" IO.puts "band(#{a}, #{b}) = #{band(a, b)}" IO.puts "bor(#{a}, #{b}) = #{bor(a, b)}" IO.puts "bxor(#{a}, #{b}) = #{bxor(a, b)}" IO.puts "bnot(#{a}) = #{bnot(a)}" IO.puts "bsl(#{a}, #{c}) = #{bsl(a, c)}" IO.puts "bsr(#{a}, #{c}) = #{bsr(a, c)}" IO.puts "\nBitwise as operator:" IO.puts "#{a} &&& #{b} = #{a &&& b}" IO.puts "#{a} ||| #{b} = #{a ||| b}" IO.puts "#{a} ^^^ #{b} = #{a ^^^ b}" IO.puts "~~~#{a} = #{~~~a}" IO.puts "#{a} <<< #{c} = #{a <<< c}" IO.puts "#{a} >>> #{c} = #{a >>> c}" end end   Bitwise_operation.test
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#Factor
Factor
USING: arrays fry kernel math.matrices sequences ; IN: rosettacode.raster.storage   ! Various utilities : meach ( matrix quot -- ) [ each ] curry each ; inline : meach-index ( matrix quot -- ) [ swap 2array ] prepose [ curry each-index ] curry each-index ; inline : mmap ( matrix quot -- matrix' ) [ map ] curry map ; inline : mmap! ( matrix quot -- matrix' ) [ map! ] curry map! ; inline : mmap-index ( matrix quot -- matrix' ) [ swap 2array ] prepose [ curry map-index ] curry map-index ; inline   : matrix-dim ( matrix -- i j ) [ length ] [ first length ] bi ; : set-Mi,j ( elt {i,j} matrix -- ) [ first2 swap ] dip nth set-nth ; : Mi,j ( {i,j} matrix -- elt ) [ first2 swap ] dip nth nth ;   ! The storage functions : <raster-image> ( width height -- image ) zero-matrix [ drop { 0 0 0 } ] mmap ; : fill-image ( {R,G,B} image -- image ) swap '[ drop _ ] mmap! ; : set-pixel ( {R,G,B} {i,j} image -- ) set-Mi,j ; inline : get-pixel ( {i,j} image -- pixel ) Mi,j ; inline  
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Factor
Factor
USING: formatting io kernel math math.matrices sequences vectors ;   : next-row ( prev -- next ) [ 1 1vector ] [ dup last [ + ] accumulate swap suffix! ] if-empty ;   : aitken ( n -- seq ) V{ } clone swap [ next-row dup ] replicate nip ;   0 50 aitken col [ 15 head ] [ last ] bi "First 15 Bell numbers:\n%[%d, %]\n\n50th: %d\n\n" printf "First 10 rows of the Bell triangle:" print 10 aitken [ "%[%d, %]\n" printf ] each
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#FreeBASIC
FreeBASIC
#define MAX 21   #macro ncp(n, p) (fact(n)/(fact(p))/(fact(n-p))) #endmacro   dim as ulongint fact(0 to MAX), bell(0 to MAX) dim as uinteger n=0, k   fact(0) = 1 for k=1 to MAX fact(k) = k*fact(k-1) next k   bell(n) = 1 print n, bell(n) for n=0 to MAX-1 for k=0 to n bell(n+1) += ncp(n, k)*bell(k) next k print n+1, bell(n+1) next n
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#D
D
import std.stdio, std.range, std.math, std.conv, std.bigint;   double[2][9] benford(R)(R seq) if (isForwardRange!R && !isInfinite!R) { typeof(return) freqs = 0; uint seqLen = 0; foreach (d; seq) if (d != 0) { freqs[d.text[0] - '1'][1]++; seqLen++; }   foreach (immutable i, ref p; freqs) p = [log10(1.0 + 1.0 / (i + 1)), p[1] / seqLen]; return freqs; }   void main() { auto fibs = recurrence!q{a[n - 1] + a[n - 2]}(1.BigInt, 1.BigInt);   writefln("%9s %9s %9s", "Actual", "Expected", "Deviation"); foreach (immutable i, immutable p; fibs.take(1000).benford) writefln("%d: %5.2f%% | %5.2f%% | %5.4f%%", i+1, p[1] * 100, p[0] * 100, abs(p[1] - p[0]) * 100); }
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#Crystal
Crystal
require "big"   class Bernoulli include Iterator(Tuple(Int32, BigRational))   def initialize @a = [] of BigRational @m = 0 end   def next @a << BigRational.new(1, @m+1) @m.downto(1) { |j| @a[j-1] = j*(@a[j-1] - @a[j]) } v = @m.odd? && @m != 1 ? BigRational.new(0, 1) : @a.first return {@m, v} ensure @m += 1 end end   b = Bernoulli.new bn = b.first(61).to_a   max_width = bn.map { |_, v| v.numerator.to_s.size }.max bn.reject { |i, v| v.zero? }.each do |i, v| puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator] end  
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#AppleScript
AppleScript
on binarySearch(n, theList, l, r) repeat until (l = r) set m to (l + r) div 2 if (item m of theList < n) then set l to m + 1 else set r to m end if end repeat   if (item l of theList is n) then return l return missing value end binarySearch   on test(n, theList, l, r) set |result| to binarySearch(n, theList, l, r) if (|result| is missing value) then return (n as text) & " is not in range " & l & " thru " & r & " of the list" else return "The first occurrence of " & n & " in range " & l & " thru " & r & " of the list is at index " & |result| end if end test   set theList to {1, 2, 3, 3, 5, 7, 7, 8, 9, 10, 11, 12} return test(7, theList, 4, 11) & linefeed & test(7, theList, 7, 12) & linefeed & test(7, theList, 1, 5)
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Clojure
Clojure
(defn score [before after] (->> (map = before after) (filter true? ,) count))   (defn merge-vecs [init vecs] (reduce (fn [counts [index x]] (assoc counts x (conj (get counts x []) index))) init vecs))   (defn frequency "Returns a collection of indecies of distinct items" [coll] (->> (map-indexed vector coll) (merge-vecs {} ,)))   (defn group-indecies [s] (->> (frequency s) vals (sort-by count ,) reverse))   (defn cycles [coll] (let [n (count (first coll)) cycle (cycle (range n)) coll (apply concat coll)] (->> (map vector coll cycle) (merge-vecs [] ,))))   (defn rotate [n coll] (let [c (count coll) n (rem (+ c n) c)] (concat (drop n coll) (take n coll))))   (defn best-shuffle [s] (let [ref (cycles (group-indecies s)) prm (apply concat (map (partial rotate 1) ref)) ref (apply concat ref)] (->> (map vector ref prm) (sort-by first ,) (map second ,) (map (partial get s) ,) (apply str ,) (#(vector s % (score s %))))))   user> (->> ["abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"] (map best-shuffle ,) vec) [["abracadabra" "bdabararaac" 0] ["seesaw" "eawess" 0] ["elk" "lke" 0] ["grrrrrr" "rgrrrrr" 5] ["up" "pu" 0] ["a" "a" 1]]
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Go
Go
package main   import ( "bytes" "fmt" )   // Strings in Go allow arbitrary bytes. They are implemented basically as // immutable byte slices and syntactic sugar. This program shows functions // required by the task on byte slices, thus it mostly highlights what // happens behind the syntactic sugar. The program does not attempt to // reproduce the immutability property of strings, as that does not seem // to be the intent of the task.   func main() { // Task point: String creation and destruction. // Strings are most often constructed from literals as in s := "binary" // With byte slices, b := []byte{'b', 'i', 'n', 'a', 'r', 'y'} fmt.Println(b) // output shows numeric form of bytes. // Go is garbage collected. There are no destruction operations.   // Task point: String assignment. // t = s assigns strings. Since strings are immutable, it is irrelevant // whether the string is copied or not. // With byte slices, the same works, var c []byte c = b fmt.Println(c)   // Task point: String comparison. // operators <, <=, ==, >=, and > work directly on strings comparing them // by lexicographic order. // With byte slices, there are standard library functions, bytes.Equal // and bytes.Compare. fmt.Println(bytes.Equal(b, c)) // prints true   // Task point: String cloning and copying. // The immutable property of Go strings makes cloning and copying // meaningless for strings. // With byte slices though, it is relevant. The assignment c = b shown // above does a reference copy, leaving both c and b based on the same // underlying data. To clone or copy the underlying data, d := make([]byte, len(b)) // allocate new space copy(d, b) // copy the data // The data can be manipulated independently now: d[1] = 'a' d[4] = 'n' fmt.Println(string(b)) // convert to string for readable output fmt.Println(string(d))   // Task point: Check if a string is empty. // Most typical for strings is s == "", but len(s) == 0 works too. // For byte slices, "" does not work, len(b) == 0 is correct. fmt.Println(len(b) == 0)   // Task point: Append a byte to a string. // The language does not provide a way to do this directly with strings. // Instead, the byte must be converted to a one-byte string first, as in, // s += string('z') // For byte slices, the language provides the append function, z := append(b, 'z') fmt.Printf("%s\n", z) // another way to get readable output   // Task point: Extract a substring from a string. // Slicing syntax is the for both strings and slices. sub := b[1:3] fmt.Println(string(sub))   // Task point: Replace every occurrence of a byte (or a string) // in a string with another string. // Go supports this with similar library functions for strings and // byte slices. Strings: t = strings.Replace(s, "n", "m", -1). // The byte slice equivalent returns a modified copy, leaving the // original byte slice untouched, f := bytes.Replace(d, []byte{'n'}, []byte{'m'}, -1) fmt.Printf("%s -> %s\n", d, f)   // Task point: Join strings. // Using slicing syntax again, with strings, // rem := s[:1] + s[3:] leaves rem == "bary". // Only the concatenation of the parts is different with byte slices, rem := append(append([]byte{}, b[:1]...), b[3:]...) fmt.Println(string(rem)) }
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Perl
Perl
use strict; use warnings; no warnings 'uninitialized'; use feature 'say'; use experimental 'signatures'; use constant Inf => 1e10;   my @tests = ( { limits => [23, 37, 43, 53, 67, 83], data => [ 95,21,94,12,99,4,70,75,83,93,52,80,57, 5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96, 6,98,40,79,97,45,64,60,29,49,36,43,55 ] }, { limits => [14, 18, 249, 312, 389, 392, 513, 591, 634, 720], data => [ 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749 ] } );   sub bisect_right ($x, $low, $high, @array) { my ($middle); while ($low < $high) { $middle = ($low + $high) / 2; $x < $array[$middle] ? $high = $middle : ($low = $middle + 1) } $low-1 }   sub bin_it ($limits, $data) { my @bins; ++$bins[ bisect_right($_, 0, @$limits-1, @$limits) ] for @$data; @bins }   sub bin_format ($limits, @bins) { my @lim = @$limits; my(@formatted); push @formatted, sprintf "[%3d, %3d) => %3d\n", $lim[$_], ($lim[$_+1] == Inf ? 'Inf' : $lim[$_+1]), $bins[$_] for 0..@lim-2; @formatted }   for (0..$#tests) { my @limits = (0, @{$tests[$_]{limits}}, Inf); say bin_format \@limits, bin_it(\@limits,\@{$tests[$_]{data}}); }
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
from collections import Counter   def basecount(dna): return sorted(Counter(dna).items())   def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)]   def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}")   if __name__ == '__main__': print("SEQUENCE:") sequence = '''\ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT''' seq_pp(sequence)  
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#ALGOL-M
ALGOL-M
begin procedure writebin(n); integer n; begin procedure inner(x); integer x; begin if x>1 then inner(x/2); writeon(if x-x/2*2=0 then "0" else "1"); end; write(""); % start new line % inner(n); end;   writebin(5); writebin(50); writebin(9000); end
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Fortran
Fortran
module RCImagePrimitive use RCImageBasic   implicit none   type point integer :: x, y end type point   private :: swapcoord   contains   subroutine swapcoord(p1, p2) integer, intent(inout) :: p1, p2 integer :: t   t = p2 p2 = p1 p1 = t end subroutine swapcoord   subroutine draw_line(img, from, to, color) type(rgbimage), intent(inout) :: img type(point), intent(in) :: from, to type(rgb), intent(in) :: color   type(point) :: rfrom, rto integer :: dx, dy, error, ystep, x, y logical :: steep   rfrom = from rto = to steep = (abs(rto%y - rfrom%y) > abs(rto%x - rfrom%x)) if ( steep ) then call swapcoord(rfrom%x, rfrom%y) call swapcoord(rto%x, rto%y) end if if ( rfrom%x > rto%x ) then call swapcoord(rfrom%x, rto%x) call swapcoord(rfrom%y, rto%y) end if   dx = rto%x - rfrom%x dy = abs(rto%y - rfrom%y) error = dx / 2 y = rfrom%y   if ( rfrom%y < rto%y ) then ystep = 1 else ystep = -1 end if   do x = rfrom%x, rto%x if ( steep ) then call put_pixel(img, y, x, color) else call put_pixel(img, x, y, color) end if error = error - dy if ( error < 0 ) then y = y + ystep error = error + dx end if end do   end subroutine draw_line   end module RCImagePrimitive
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Objective-C
Objective-C
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#OCaml
OCaml
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Octave
Octave
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Logo
Logo
; List of abbreviated compass point labels make "compass_points [ N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW ]   ; List of angles to test make "test_angles [ 0.00 16.87 16.88 33.75 50.62 50.63 67.50 84.37 84.38 101.25 118.12 118.13 135.00 151.87 151.88 168.75 185.62 185.63 202.50 219.37 219.38 236.25 253.12 253.13 270.00 286.87 286.88 303.75 320.62 320.63 337.50 354.37 354.38 ]   ; make comparisons case-sensitive make "caseignoredp "false   ; String utilities: search and replace to replace_in :src :from :to output map [ ifelse equalp ? :from [:to] [?] ] :src end   ; pad with spaces to pad :string :length output cascade [lessp :length count ?] [word ? "\ ] :string end   ; capitalize first letter to capitalize :string output word (uppercase first :string) butfirst :string end   ; convert compass point abbreviation to full text of label to expand_point :abbr foreach [[N north] [E east] [S south] [W west] [b \ by\ ]] [ make "abbr replace_in :abbr (first ?) (last ?) ] output capitalize :abbr end   ; modulus function that returns 1..N instead of 0..N-1 to adjusted_modulo :n :d output sum 1 modulo (difference :n 1) :d end   ; convert a compass angle from degrees into a box index (1..32) to compass_point :degrees make "degrees modulo :degrees 360 output adjusted_modulo (sum 1 int quotient (sum :degrees 5.625) 11.25) 32 end   ; Now output the table of test data print (sentence (pad "Degrees 7) "\| (pad "Closest\ Point 18) "\| "Index ) foreach :test_angles [ local "index make "index compass_point ? local "abbr make "abbr item :index :compass_points local "label make "label expand_point :abbr print (sentence (form ? 7 2) "\| (pad :label 18) "\| (form :index 2 0) ) ]   ; and exit bye  
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#Erlang
Erlang
  -module(bitwise_operations).   -export([test/0]).   test() -> A = 255, B = 170, io:format("~p band ~p = ~p\n",[A,B,A band B]), io:format("~p bor ~p = ~p\n",[A,B,A bor B]), io:format("~p bxor ~p = ~p\n",[A,B,A bxor B]), io:format("not ~p = ~p\n",[A,bnot A]), io:format("~p bsl ~p = ~p\n",[A,B,A bsl B]), io:format("~p bsr ~p = ~p\n",[A,B,A bsr B]).  
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_RBUTTONDOWN 516 #DEFINE WM_CLOSE 16   FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 300, 200) CENTER(ME) SHOW(ME)   BEGIN EVENTS SELECT CASE CBMSG CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) CASE WM_CLOSE ' Clean up FBSL.RELEASEDC(ME, FBSL.GETDC) END SELECT END EVENTS
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Go
Go
package main   import ( "fmt" "math/big" )   func bellTriangle(n int) [][]*big.Int { tri := make([][]*big.Int, n) for i := 0; i < n; i++ { tri[i] = make([]*big.Int, i) for j := 0; j < i; j++ { tri[i][j] = new(big.Int) } } tri[1][0].SetUint64(1) for i := 2; i < n; i++ { tri[i][0].Set(tri[i-1][i-2]) for j := 1; j < i; j++ { tri[i][j].Add(tri[i][j-1], tri[i-1][j-1]) } } return tri }   func main() { bt := bellTriangle(51) fmt.Println("First fifteen and fiftieth Bell numbers:") for i := 1; i <= 15; i++ { fmt.Printf("%2d: %d\n", i, bt[i][0]) } fmt.Println("50:", bt[50][0]) fmt.Println("\nThe first ten rows of Bell's triangle:") for i := 1; i <= 10; i++ { fmt.Println(bt[i]) } }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Delphi
Delphi
defmodule Benfords_law do def distribution(n), do: :math.log10( 1 + (1 / n) )   def task(total \\ 1000) do IO.puts "Digit Actual Benfords expected" fib(total) |> Enum.group_by(fn i -> hd(to_char_list(i)) end) |> Enum.map(fn {key,list} -> {key - ?0, length(list)} end) |> Enum.sort |> Enum.each(fn {x,len} -> IO.puts "#{x} #{len / total} #{distribution(x)}" end) end   defp fib(n) do # suppresses zero Stream.unfold({1,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(n) end end   Benfords_law.task
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Elixir
Elixir
defmodule Benfords_law do def distribution(n), do: :math.log10( 1 + (1 / n) )   def task(total \\ 1000) do IO.puts "Digit Actual Benfords expected" fib(total) |> Enum.group_by(fn i -> hd(to_char_list(i)) end) |> Enum.map(fn {key,list} -> {key - ?0, length(list)} end) |> Enum.sort |> Enum.each(fn {x,len} -> IO.puts "#{x} #{len / total} #{distribution(x)}" end) end   defp fib(n) do # suppresses zero Stream.unfold({1,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(n) end end   Benfords_law.task
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#D
D
import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational;   auto bernoulli(in uint n) pure nothrow /*@safe*/ { auto A = new Rational[n + 1]; foreach (immutable m; 0 .. n + 1) { A[m] = Rational(1, m + 1); foreach_reverse (immutable j; 1 .. m + 1) A[j - 1] = j * (A[j - 1] - A[j]); } return A[0]; }   void main() { immutable berns = 61.iota.map!bernoulli.enumerate.filter!(t => t[1]).array; immutable width = berns.map!(b => b[1].numerator.text.length).reduce!max; foreach (immutable b; berns) writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof); }
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program binsearch.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .ascii "Value find at index : " sMessValeur: .fill 11, 1, ' ' @ size => 11 szCarriageReturn: .asciz "\n" sMessRecursif: .asciz "Recursive search : \n" sMessNotFound: .asciz "Value not found. \n"   .equ NBELEMENTS, 9 TableNumber: .int 4,6,7,10,11,15,22,30,35   /*********************************/ /* UnInitialized data */ /*********************************/ .bss /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program mov r0,#4 @ search first value ldr r1,iAdrTableNumber @ address number table mov r2,#NBELEMENTS @ number of élements bl bSearch ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message   mov r0,#11 @ search median value ldr r1,iAdrTableNumber mov r2,#NBELEMENTS bl bSearch ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message   mov r0,#12 @value not found ldr r1,iAdrTableNumber mov r2,#NBELEMENTS bl bSearch cmp r0,#-1 bne 2f ldr r0,iAdrsMessNotFound bl affichageMess b 3f 2: ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message 3: mov r0,#35 @ search last value ldr r1,iAdrTableNumber mov r2,#NBELEMENTS bl bSearch ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message /****************************************/ /* recursive */ /****************************************/ ldr r0,iAdrsMessRecursif bl affichageMess @ display message   mov r0,#4 @ search first value ldr r1,iAdrTableNumber mov r2,#0 @ low index of elements mov r3,#NBELEMENTS - 1 @ high index of elements bl bSearchR ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message   mov r0,#11 ldr r1,iAdrTableNumber mov r2,#0 mov r3,#NBELEMENTS - 1 bl bSearchR ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message   mov r0,#12 ldr r1,iAdrTableNumber mov r2,#0 mov r3,#NBELEMENTS - 1 bl bSearchR cmp r0,#-1 bne 2f ldr r0,iAdrsMessNotFound bl affichageMess b 3f 2: ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message 3: mov r0,#35 ldr r1,iAdrTableNumber mov r2,#0 mov r3,#NBELEMENTS - 1 bl bSearchR ldr r1,iAdrsMessValeur @ display value bl conversion10 @ call function ldr r0,iAdrsMessResult bl affichageMess @ display message   100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrsMessValeur: .int sMessValeur iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessResult: .int sMessResult iAdrsMessRecursif: .int sMessRecursif iAdrsMessNotFound: .int sMessNotFound iAdrTableNumber: .int TableNumber   /******************************************************************/ /* binary search iterative */ /******************************************************************/ /* r0 contains the value to search */ /* r1 contains the adress of table */ /* r2 contains the number of elements */ /* r0 return index or -1 if not find */ bSearch: push {r2-r5,lr} @ save registers mov r3,#0 @ low index sub r4,r2,#1 @ high index = number of elements - 1 1: cmp r3,r4 movgt r0,#-1 @not found bgt 100f add r2,r3,r4 @ compute (low + high) /2 lsr r2,#1 ldr r5,[r1,r2,lsl #2] @ load value of table at index r2 cmp r5,r0 moveq r0,r2 @ find !!! beq 100f addlt r3,r2,#1 @ lower -> index low = index + 1 subgt r4,r2,#1 @ bigger -> index high = index - 1 b 1b @ and loop 100: pop {r2-r5,lr} bx lr @ return /******************************************************************/ /* binary search recursif */ /******************************************************************/ /* r0 contains the value to search */ /* r1 contains the adress of table */ /* r2 contains the low index of elements */ /* r3 contains the high index of elements */ /* r0 return index or -1 if not find */ bSearchR: push {r2-r5,lr} @ save registers cmp r3,r2 @ index high < low ? movlt r0,#-1 @ yes -> not found blt 100f   add r4,r2,r3 @ compute (low + high) /2 lsr r4,#1 ldr r5,[r1,r4,lsl #2] @ load value of table at index r4 cmp r5,r0 moveq r0,r4 @ find !!! beq 100f   bgt 1f @ bigger ? add r2,r4,#1 @ no new search with low = index + 1 bl bSearchR b 100f 1: @ bigger sub r3,r4,#1 @ new search with high = index - 1 bl bSearchR 100: pop {r2-r5,lr} bx lr @ return /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur des 2 registres bx lr @ return /******************************************************************/ /* Converting a register to a decimal unsigned */ /******************************************************************/ /* r0 contains value and r1 address area */ /* r0 return size of result (no zero final in area) */ /* area size => 11 bytes */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL   1: @ start loop bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ else previous position bne 1b @ and loop @ and move digit from left of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] add r2,#1 add r4,#1 cmp r2,#LGZONECAL ble 2b @ and move spaces in end on area mov r0,r4 @ result length mov r1,#' ' @ space 3: strb r1,[r3,r4] @ store space in area add r4,#1 @ next position cmp r4,#LGZONECAL ble 3b @ loop if r4 <= area size   100: pop {r1-r4,lr} @ restaur registres bx lr @return   /***************************************************/ /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} mov r4,r0 @ save value //mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3 //movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3 ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2 umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function iMagicNumber: .int 0xCCCCCCCD    
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements 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
#Common_Lisp
Common Lisp
(defun count-equal-chars (string1 string2) (loop for c1 across string1 and c2 across string2 count (char= c1 c2)))   (defun shuffle (string) (let ((length (length string)) (result (copy-seq string))) (dotimes (i length result) (dotimes (j length) (when (and (/= i j) (char/= (aref string i) (aref result j)) (char/= (aref string j) (aref result i))) (rotatef (aref result i) (aref result j)))))))   (defun best-shuffle (list) (dolist (string list) (let ((shuffled (shuffle string))) (format t "~%~a ~a (~a)" string shuffled (count-equal-chars string shuffled)))))   (best-shuffle '("abracadabra" "seesaw" "elk" "grrrrrr" "up" "a"))
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Groovy
Groovy
import java.nio.charset.StandardCharsets   class MutableByteString { private byte[] bytes private int length   MutableByteString(byte... bytes) { setInternal(bytes) }   int length() { return length }   boolean isEmpty() { return length == 0 }   byte get(int index) { return bytes[check(index)] }   void set(byte[] bytes) { setInternal(bytes) }   void set(int index, byte b) { bytes[check(index)] = b }   void append(byte b) { if (length >= bytes.length) { int len = 2 * bytes.length if (len < 0) { len = Integer.MAX_VALUE } bytes = Arrays.copyOf(bytes, len) } bytes[length] = b length++ }   MutableByteString substring(int from, int to) { return new MutableByteString(Arrays.copyOfRange(bytes, from, to)) }   void replace(byte[] from, byte[] to) { ByteArrayOutputStream copy = new ByteArrayOutputStream() if (from.length == 0) { for (byte b : bytes) { copy.write(to, 0, to.length) copy.write(b) } copy.write(to, 0, to.length) } else { for (int i = 0; i < length; i++) { if (regionEqualsImpl(i, from)) { copy.write(to, 0, to.length) i += from.length - 1 } else { copy.write(bytes[i]) } } } set(copy.toByteArray()) }   boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) { if (Math.max(offset, otherOffset) + len < 0) { return false } if (offset + len > length || otherOffset + len > other.length()) { return false } for (int i = 0; i < len; i++) { if (bytes[offset + i] != other.get(otherOffset + i)) { return false } } return true }   String toHexString() { char[] hex = new char[2 * length] for (int i = 0; i < length; i++) { hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F) hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F) } return new String(hex) }   String toStringUtf8() { return new String(bytes, 0, length, StandardCharsets.UTF_8) }   private void setInternal(byte[] bytes) { this.bytes = bytes.clone() this.length = bytes.length }   private boolean regionEqualsImpl(int offset, byte[] other) { int len = other.length if (offset < 0 || offset + len < 0) return false if (offset + len > length) return false for (int i = 0; i < len; i++) { if (bytes[offset + i] != other[i]) return false } return true }   private int check(int index) { if (index < 0 || index >= length) throw new IndexOutOfBoundsException(String.valueOf(index)) return index } }
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Phix
Phix
with javascript_semantics function bin_it(sequence limits, data) -- Bin data according to (ascending) limits. sequence bins = repeat(0,length(limits)+1) -- adds under/over range bins too for i=1 to length(data) do integer bdx = binary_search(data[i],limits) bdx = abs(bdx)+(bdx>0) bins[bdx] += 1 end for return bins end function procedure bin_print(sequence limits, bins) printf(1," < %3d := %3d\n",{limits[1],bins[1]}) for i=2 to length(limits) do printf(1,">= %3d and < %3d := %3d\n",{limits[i-1],limits[i],bins[i]}) end for printf(1,">= %3d  := %3d\n\n",{limits[$],bins[$]}) end procedure sequence limits, data printf(1,"Example 1:\n") limits = {23, 37, 43, 53, 67, 83} data = {95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55} bin_print(limits, bin_it(limits, data)) printf(1,"Example 2:\n") limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} data = {445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749} bin_print(limits, bin_it(limits, data))
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Quackery
Quackery
  [ over size - space swap of swap join ] is justify ( $ n --> $ )   [ 0 swap [ dup $ "" != while cr over number$ 4 justify echo$ 5 times [ dup $ "" = iff conclude done sp 10 split swap echo$ ] dip [ 50 + ] again ] 2drop ] is prettyprint ( $ --> )   [ stack ] is adenine ( --> s ) [ stack ] is cytosine ( --> s ) [ stack ] is guanine ( --> s ) [ stack ] is thymine ( --> s )   [ table adenine cytosine guanine thymine ] is bases ( --> [ )   [ 4 times [ 0 i^ bases put ] witheach [ $ "ACGT" find bases 1 swap tally ] 4 times [ sp i^ bases dup echo sp share echo cr ] 0 4 times [ i^ bases take + ] cr say " total " echo ] is tallybases ( [ --> )   $ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" $ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" join $ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" join $ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" join $ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" join $ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" join $ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" join $ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" join $ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" join $ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" join   dup prettyprint cr cr tallybases
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#R
R
  #Data gene1 <- "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   #Analysis: gene2 <- gsub("\n", "", gene1) #remove \n chars gene3 <- strsplit(gene2, split = character(0)) #split into list gene4 <- gene3[[1]] #pull out character vector from list basecounts <- as.data.frame(table(gene4)) #make table of base counts   #quick helper function to print table results print_row <- function(df, row){paste0(df$gene[row],": ", df$Freq[row])}   #Print Function for Data with Results: cat(" Data: \n", " 1:",substring(gene2, 1, 50),"\n", " 51:",substring(gene2, 51, 100),"\n", "101:",substring(gene2, 101, 150),"\n", "151:",substring(gene2, 151, 200),"\n", "201:",substring(gene2, 201, 250),"\n", "251:",substring(gene2, 251, 300),"\n", "301:",substring(gene2, 301, 350),"\n", "351:",substring(gene2, 351, 400),"\n", "401:",substring(gene2, 401, 450),"\n", "451:",substring(gene2, 451, 500),"\n", "\n", "Base Count Results: \n", print_row(basecounts,1), "\n", print_row(basecounts,2), "\n", print_row(basecounts,3), "\n", print_row(basecounts,4), "\n", "\n", "Total Base Count:", paste(length(gene4)) )    
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#APL
APL
base2←2∘⊥⍣¯1
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#FreeBASIC
FreeBASIC
' version 16-09-2015 ' compile with: fbc -s console ' OR compile with: fbc -s gui   ' Ported from the C version Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, Col As Integer = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) Dim As Integer sx = IIf(x0 < x1, 1, -1) Dim As Integer sy = IIf(y0 < y1, 1, -1) Dim As Integer er = IIf(dx > dy, dx, -dy) \ 2, e2   Do PSet(x0, y0), col If (x0 = x1) And (y0 = y1) Then Exit Do e2 = er If e2 > -dx Then Er -= dy : x0 += sx If e2 < dy Then Er += dx : y0 += sy Loop   End Sub   ' ------=< MAIN >=------   Dim As Double x0, y0, x1, y1   ScreenRes 400, 400, 32 WindowTitle" Press key to end demo" Randomize Timer   Do Cls For a As Integer = 1 To 20 Br_line(Rnd*380+10, Rnd*380+10, Rnd*380+10, Rnd*380+10, Rnd*&hFFFFFF) Next Sleep 2000 Loop Until InKey <> "" ' loop until a key is pressed   End
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oforth
Oforth
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Ol
Ol
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Lua
Lua
-- List of abbreviated compass point labels compass_points = { "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN", "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE", "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS", "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW" }   -- List of angles to test test_angles = { 0.00, 16.87, 16.88, 33.75, 50.62, 50.63, 67.50, 84.37, 84.38, 101.25, 118.12, 118.13, 135.00, 151.87, 151.88, 168.75, 185.62, 185.63, 202.50, 219.37, 219.38, 236.25, 253.12, 253.13, 270.00, 286.87, 286.88, 303.75, 320.62, 320.63, 337.50, 354.37, 354.38 }     -- capitalize a string function capitalize(s) return s:sub(1,1):upper() .. s:sub(2) end   -- convert compass point abbreviation to full text of label function expand_point(abbr) for from, to in pairs( { N="north", E="east", S="south", W="west", b=" by " }) do abbr = abbr:gsub(from, to) end return capitalize(abbr) end   -- modulus function that returns 1..N instead of 0..N-1 function adjusted_modulo(n, d) return 1 + (n - 1) % d end   -- convert a compass angle from degrees into a box index (1..32) function compass_point(degrees) degrees = degrees % 360 return adjusted_modulo(1 + math.floor( (degrees+5.625) / 11.25), 32) end   -- Now output the table of test data header_format = "%-7s | %-18s | %s" row_format = "%7.2f | %-18s | %2d" print(header_format:format("Degrees", "Closest Point", "Index")) for i, angle in ipairs(test_angles) do index = compass_point(angle) abbr = compass_points[index] label = expand_point(abbr) print(row_format:format(angle, label, index)) end
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#F.23
F#
let bitwise a b = printfn "a and b: %d" (a &&& b) printfn "a or b: %d" (a ||| b) printfn "a xor b: %d" (a ^^^ b) printfn "not a: %d" (~~~a) printfn "a shl b: %d" (a <<< b) printfn "a shr b: %d" (a >>> b) // arithmetic shift printfn "a shr b: %d" ((uint32 a) >>> b) // logical shift // No rotation operators.
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#Forth
Forth
hex 0000ff constant red 00ff00 constant green ff0000 constant blue decimal   1 cells constant pixel : pixels cells ;   : bdim ( bmp -- w h ) 2@ ; : bheight ( bmp -- h ) @ ; : bwidth ( bmp -- w ) bdim drop ; : bdata ( bmp -- addr ) 2 cells + ;   : bitmap ( w h -- bmp ) 2dup * pixels bdata allocate throw dup >r 2! r> ;   : bfill ( pixel bmp -- ) dup bdata swap bdim * pixels bounds do dup i ! pixel +loop drop ;   : bxy ( x y bmp -- addr ) dup >r bwidth * + pixels r> bdata + ;   : b@ ( x y bmp -- pixel ) bxy @ ; : b! ( pixel x y bmp -- ) bxy ! ;   : bshow ( bmp -- ) hex dup bdim 0 do cr dup 0 do over i j rot b@ if [char] * else bl then emit \ 7 u.r loop loop 2drop decimal ;   4 3 bitmap value test red test bfill test bshow cr
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Groovy
Groovy
class Bell { private static class BellTriangle { private List<Integer> arr   BellTriangle(int n) { int length = (int) (n * (n + 1) / 2) arr = new ArrayList<>(length) for (int i = 0; i < length; ++i) { arr.add(0) }   set(1, 0, 1) for (int i = 2; i <= n; ++i) { set(i, 0, get(i - 1, i - 2)) for (int j = 1; j < i; ++j) { int value = get(i, j - 1) + get(i - 1, j - 1) set(i, j, value) } } }   private static int index(int row, int col) { if (row > 0 && col >= 0 && col < row) { return row * (row - 1) / 2 + col } else { throw new IllegalArgumentException() } }   int get(int row, int col) { int i = index(row, col) return arr.get(i) }   void set(int row, int col, int value) { int i = index(row, col) arr.set(i, value) } }   static void main(String[] args) { final int rows = 15 BellTriangle bt = new BellTriangle(rows)   System.out.println("First fifteen Bell numbers:") for (int i = 0; i < rows; ++i) { System.out.printf("%2d: %d\n", i + 1, bt.get(i + 1, 0)) }   for (int i = 1; i <= 10; ++i) { System.out.print(bt.get(i, 0)) for (int j = 1; j < i; ++j) { System.out.printf(", %d", bt.get(i, j)) } System.out.println() } } }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Erlang
Erlang
  -module( benfords_law ). -export( [actual_distribution/1, distribution/1, task/0] ).   actual_distribution( Ns ) -> lists:foldl( fun first_digit_count/2, dict:new(), Ns ).   distribution( N ) -> math:log10( 1 + (1 / N) ).   task() -> Total = 1000, Fibonaccis = fib( Total ), Actual_dict = actual_distribution( Fibonaccis ), Keys = lists:sort( dict:fetch_keys( Actual_dict) ), io:fwrite( "Digit Actual Benfords expected~n" ), [io:fwrite("~p ~p ~p~n", [X, dict:fetch(X, Actual_dict) / Total, distribution(X)]) || X <- Keys].       fib( N ) -> fib( N, 0, 1, [] ). fib( 0, Current, _, Acc ) -> lists:reverse( [Current | Acc] ); fib( N, Current, Next, Acc ) -> fib( N-1, Next, Current+Next, [Current | Acc] ).   first_digit_count( 0, Dict ) -> Dict; first_digit_count( N, Dict ) -> [Key | _] = erlang:integer_to_list( N ), dict:update_counter( Key - 48, 1, Dict ).  
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#Delphi
Delphi
  program Bernoulli_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigRationals;   function b(n: Integer): BigRational; begin var a: TArray<BigRational>; SetLength(a, n + 1); for var m := 0 to High(a) do begin a[m] := BigRational.Create(1, m + 1); for var j := m downto 1 do begin a[j - 1] := (a[j - 1] - a[j]) * j; end; end; Result := a[0]; end;   begin for var n := 0 to 60 do begin var bb := b(n); if bb.Numerator.BitLength > 0 then writeln(format('B(%2d) =%45s/%s', [n, bb.Numerator.ToString, bb.Denominator.ToString])); end; readln; end.
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#Arturo
Arturo
binarySearch: function [arr,val,low,high][ if high < low -> return ø mid: shr low+high 1 case [val] when? [< arr\[mid]] -> return binarySearch arr val low mid-1 when? [> arr\[mid]] -> return binarySearch arr val mid+1 high else -> return mid ]   ary: [ 0 1 4 5 6 7 8 9 12 26 45 67 78 90 98 123 211 234 456 769 865 2345 3215 14345 24324 ]   loop [0 42 45 24324 99999] 'v [ i: binarySearch ary v 0 (size ary)-1 if? not? null? i -> print ["found" v "at index:" i] else -> print [v "not found"] ]
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements 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
#Crystal
Crystal
def best_shuffle(s) # Fill _pos_ with positions in the order # that we want to fill them. pos = [] of Int32 # g["a"] = [2, 4] implies that s[2] == s[4] == "a" g = s.size.times.group_by { |i| s[i] }   # k sorts letters from low to high count # k = g.sort_by { |k, v| v.length }.map { |k, v| k } # in Ruby # k = g.to_a.sort_by { |(k, v)| v.size }.map { |(k, v)| k } # Crystal direct k = g.to_a.sort_by { |h| h[1].size }.map { |h| h[0] } # Crystal shorter   until g.empty? k.each do |letter| g.has_key?(letter) || next # next unless g.has_key? letter pos << g[letter].pop g[letter].empty? && g.delete letter # g.delete(letter) if g[letter].empty? end end   # Now fill in _new_ with _letters_ according to each position # in _pos_, but skip ahead in _letters_ if we can avoid # matching characters that way. letters = s.dup new = "?" * s.size   until letters.empty? i, p = 0, pos.pop while letters[i] == s[p] && i < (letters.size - 1); i += 1 end # new[p] = letters.slice! i # in Ruby new = new.sub(p, letters[i]); letters = letters.sub(i, "") end score = new.chars.zip(s.chars).count { |c, d| c == d } {new, score} end   %w(abracadabra seesaw elk grrrrrr up a).each do |word| # puts "%s, %s, (%d)" % [word, *best_shuffle(word)] # in Ruby new, score = best_shuffle(word) puts "%s, %s, (%d)" % [word, new, score] end
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Haskell
Haskell
import Text.Regex {- The above import is needed only for the last function. It is used there purely for readability and conciseness -}   {- Assigning a string to a 'variable'. We're being explicit about it just for show. Haskell would be able to figure out the type of "world" -} string = "world" :: String
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Icon_and_Unicon
Icon and Unicon
s := "\x00" # strings can contain any value, even nulls s := "abc" # create a string s := &null # destroy a string (garbage collect value of s; set new value to &null) v := s # assignment s == t # expression s equals t s << t # expression s less than t s <<= t # expression s less than or equal to t v := s # strings are immutable, no copying or cloning are needed s == "" # equal empty string *s = 0 # string length is zero s ||:= "a" # append a byte "a" to s via concatenation t := s[2+:3] # t is set to position 2 for 3 characters s := replace(s,s2,s3) # IPL replace function s := s1 || s2 # concatenation (joining) of strings