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/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   +½.
#Icon_and_Unicon
Icon and Unicon
link "rational"   procedure main(args) limit := integer(!args) | 60 every b := bernoulli(i := 0 to limit) do if b.numer > 0 then write(right(i,3),": ",align(rat2str(b),60)) end   procedure bernoulli(n) (A := table(0))[0] := rational(1,1,1) every m := 1 to n do { A[m] := rational(1,m+1,1) every j := m to 1 by -1 do A[j-1] := mpyrat(rational(j,1,1), subrat(A[j-1],A[j])) } return A[0] end   procedure align(r,n) return repl(" ",n-find("/",r))||r 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.
#Chapel
Chapel
proc binsearch(A:[], value) { var low = A.domain.dim(1).low; var high = A.domain.dim(1).high; while (low <= high) { var mid = (low + high) / 2;   if A(mid) > value then high = mid - 1; else if A(mid) < value then low = mid + 1; else return mid; } return 0; }   writeln(binsearch([3, 4, 6, 9, 11], 9));
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
#JavaScript
JavaScript
function raze(a) { // like .join('') except producing an array instead of a string var r= []; for (var j= 0; j<a.length; j++) for (var k= 0; k<a[j].length; k++) r.push(a[j][k]); return r; } function shuffle(y) { var len= y.length; for (var j= 0; j < len; j++) { var i= Math.floor(Math.random()*len); var t= y[i]; y[i]= y[j]; y[j]= t; } return y; } function bestShuf(txt) { var chs= txt.split(''); var gr= {}; var mx= 0; for (var j= 0; j<chs.length; j++) { var ch= chs[j]; if (null == gr[ch]) gr[ch]= []; gr[ch].push(j); if (mx < gr[ch].length) mx++; } var inds= []; for (var ch in gr) inds.push(shuffle(gr[ch])); var ndx= raze(inds); var cycles= []; for (var k= 0; k < mx; k++) cycles[k]= []; for (var j= 0; j<chs.length; j++) cycles[j%mx].push(ndx[j]); var ref= raze(cycles); for (var k= 0; k < mx; k++) cycles[k].push(cycles[k].shift()); var prm= raze(cycles); var shf= []; for (var j= 0; j<chs.length; j++) shf[ref[j]]= chs[prm[j]]; return shf.join(''); }   function disp(ex) { var r= bestShuf(ex); var n= 0; for (var j= 0; j<ex.length; j++) n+= ex.substr(j, 1) == r.substr(j,1) ?1 :0; return ex+', '+r+', ('+n+')'; }
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.
#Phix
Phix
with javascript_semantics string s = "abc" s = x"ef bb bf" -- explicit binary string (the utf8 BOM) s[2] = 0 s[3] = 'z' if s="\#EF\0z" then puts(1,"ok\n") end if string t = s t[1..2] = "xy" -- s remains unaltered ?t -- "xyz" t = "food" ?t t[2..3] = 'e' ?t -- "feed" t[3..2] = "ast" ?t -- "feasted" t[3..-2] = "" ?t -- "fed" if length(t)=0 then puts(1,"t is empty\n") end if if t!="" then puts(1,"t is not empty\n") end if t = "be" t &= 't' ?t -- bet t = 'a'&t ?t -- abet ?t[2..3] -- be ?substitute(t,"be","bbo") -- abbot ?substitute(t,"be","dep") -- adept t = substitute(t,"be","dep") -- to actually modify t ?join({"abc","def","ghi"}) -- "abc def ghi" ?join({"abc","def","ghi"},"") -- "abcdefghi" ?join({"abc","def","ghi"},"\n") -- "abc\ndef\nghi"
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.
#bc
bc
obase = 2 5 50 9000 quit
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.
#Metal
Metal
void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end);   void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end) { int x = int(start.x); int y = int(start.y);   int dx = abs(x - int(end.x)); int dy = abs(y - int(end.y));   int sx = start.x < end.x ? 1 : -1; int sy = start.y < end.y ? 1 : -1;   int err = (dx > dy ? dx : -dy) / 2;   while (true) { targetTexture.write(float4(1.0), uint2(x, y));   if (x == int(end.x) && y == int(end.y)) { break; }   int e2 = err;   if (e2 > -dx) { err -= dy; x += sx; }   if (e2 < dy) { err += dx; y += sy; } } }
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
#Sather
Sather
v:BOOL := true; -- ok i:INT := 1; v := 1; -- wrong if i then ... end; -- wrong: if requires a bool! -- BUT v := 1.bool; -- ok if i.bool then ... end; -- ok
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
#Scala
Scala
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
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
#Scheme
Scheme
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
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)..
#Perl
Perl
use utf8;   my @names = ( "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", ); my @angles = (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);   for (@angles) { my $i = int(($_ * 32 / 360) + .5) % 32; printf "%3d %18s %6.2f°\n", $i + 1, $names[$i], $_; }
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.
#HPPPL
HPPPL
EXPORT BITOPS(a, b) BEGIN PRINT(BITAND(a, b)); PRINT(BITOR(a, b)); PRINT(BITXOR(a, b)); PRINT(BITNOT(a)); PRINT(BITSL(a, b)); PRINT(BITSR(a, b)); // HPPPL has no builtin rotates or arithmetic right shift. END;
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.
#M2000_Interpreter
M2000 Interpreter
  \ Bitmap width in pixels, height in pixels \ Return a group object with some lambda as members: SetPixel, GetPixel, Image$ \ copyimage \ using Copy x, y Use Image$ we can display image$ to x, y as twips \ we can use x*twipsx, y*twipsy for x,y as pixels Function Bitmap (x as long, y as long) { if x<1 or y<1 then Error "Wrong dimensions" structure rgb { red as byte green as byte blue as byte } m=len(rgb)*x mod 4 if m>0 then m=4-m ' add some bytes to raster line m+=len(rgb) *x Structure rasterline { { pad as byte*m } \\ union pad+hline hline as rgb*x }   Structure Raster { magic as integer*4 w as integer*4 h as integer*4 lines as rasterline*y } Buffer Clear Image1 as Raster \\ 24 chars as header to be used from bitmap render build in functions Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) \\ fill white (all 255) \\ Str$(string) convert to ascii, so we get all characters from words width to byte width Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) Buffer Clear Pad as Byte*4 SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ where=alines+3*x+blines*y if c>0 then c=color(c) c-! Return Pad, 0:=c as long Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte   } GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ where=alines+3*x+blines*y =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) } StrDib$=Lambda$ Image1, Raster -> { =Eval$(Image1, 0, Len(Raster)) } CopyImage=Lambda Image1 (image$) -> { if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { Return Image1, 0:=Image$ } Else Error "Can't Copy Image" } Group Bitmap { SetPixel=SetPixel GetPixel=GetPixel Image$=StrDib$ Copy=CopyImage } =Bitmap } A=Bitmap(100,100) Call A.SetPixel(50,50, color(128,0,255)) Print A.GetPixel(50,50)=color(128,0,255) \\ display image to screen at 100, 50 pixel copy 100*twipsx,50*twipsy use A.Image$() A1=Bitmap(100,100) Call A1.copy(A.Image$()) copy 500*twipsx,50*twipsy use A1.Image$()    
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.
#Maple
Maple
allocateImg := proc(width, height) return Array(1..width, 1..height, 1..3); end proc: fillColor := proc(img, rgb::list) local i; for i from 1 to 3 do img[..,..,i] := map(x->rgb[i], img[..,..,i]): end do: end proc: setColor := proc(x, y, img, rgb::list) local i: for i from 1 to 3 do img[x,y,i] := rgb[i]: end do: end proc: getColor := proc(x,y,img) local rgb,i: rgb := Array(1..3): for i from 1 to 3 do rgb(i) := img[x,y,i]: end do: return rgb: end proc:
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
#Python
Python
def bellTriangle(n): tri = [None] * n for i in xrange(n): tri[i] = [0] * i tri[1][0] = 1 for i in xrange(2, n): tri[i][0] = tri[i - 1][i - 2] for j in xrange(1, i): tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] return tri   def main(): bt = bellTriangle(51) print "First fifteen and fiftieth Bell numbers:" for i in xrange(1, 16): print "%2d: %d" % (i, bt[i][0]) print "50:", bt[50][0] print print "The first ten rows of Bell's triangle:" for i in xrange(1, 11): print bt[i]   main()
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
#Quackery
Quackery
[ ' [ [ 1 ] ] ' [ 1 ] rot 1 - times [ dup -1 peek nested swap witheach [ over -1 peek + join ] tuck nested join swap ] drop ] is bell's-triangle ( n --> [ )   [ bell's-triangle [] swap witheach [ 0 peek join ] ] is bell-numbers ( n --> [ )   say "First fifteen Bell numbers:" cr 15 bell-numbers echo cr cr say "Fiftieth Bell number:" cr 50 bell-numbers -1 peek echo cr cr say "First ten rows of Bell's triangle:" cr 10 bell's-triangle witheach [ echo cr ]
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 .
#Liberty_BASIC
Liberty BASIC
  dim bin(9)   N=1000 for i = 0 to N-1 num$ = str$(fiboI(i)) d=val(left$(num$,1)) 'print num$, d bin(d)=bin(d)+1 next print   print "Digit", "Actual freq", "Expected freq" for i = 1 to 9 print i, bin(i)/N, using("#.###", P(i)) next     function P(d) P = log10(d+1)-log10(d) end function   function log10(x) log10 = log(x)/log(10) end function   function fiboI(n) a = 0 b = 1 for i = 1 to n temp = a + b a = b b = temp next i fiboI = a end function  
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   +½.
#J
J
B=: {.&1 %. (i. ! ])@>:@i.@x:
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.
#Clojure
Clojure
(defn bsearch ([coll t] (bsearch coll 0 (dec (count coll)) t)) ([coll l u t] (if (> l u) -1 (let [m (quot (+ l u) 2) mth (nth coll m)] (cond ; the middle element is greater than t ; so search the lower half (> mth t) (recur coll l (dec m) t) ; the middle element is less than t ; so search the upper half (< mth t) (recur coll (inc m) u t) ; we've found our target ; so return its index (= mth t) m)))))
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
#jq
jq
def count(s): reduce s as $i (0;.+1);   def swap($i;$j): .[$i] as $x | .[$i] = .[$j] | .[$j] = $x;   # Input: an array # Output: a best shuffle def bestShuffleArray: . as $s | reduce range(0; length) as $i (.; . as $t | (first(range(0; length) | select( $i != . and $t[$i] != $s[.] and $s[$i] != $t[.] and $t[$i] != $t[.])) as $j | swap($i;$j)) // $t # fallback );   # Award 1 for every spot which changed: def score($base): . as $in | count( range(0;length) | select($base[.] != $in[.]) );   # Input: a string # Output: INPUT, BESTSHUFFLE, (NUMBER) def bestShuffle: . as $in | explode | . as $s | bestShuffleArray | "\($in), \(implode), (\( length - score($s) ))" ;
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
#Julia
Julia
# v0.6   function bestshuffle(str::String)::Tuple{String,Int} s = Vector{Char}(str)   # Count the supply of characters. cnt = Dict{Char,Int}(c => 0 for c in s) for c in s; cnt[c] += 1 end   # Allocate the result r = similar(s) for (i, x) in enumerate(s) # Find the best character to replace x. best = x rankb = -2 for (c, rankc) in cnt # Prefer characters with more supply. # (Save characters with less supply.) # Avoid identical characters. if c == x; rankc = -1 end if rankc > rankb best = c rankb = rankc end end   # Add character to list. Remove it from supply. r[i] = best cnt[best] -= 1 if cnt[best] == 0; delete!(cnt, best) end end   # If the final letter became stuck (as "ababcd" became "bacabd", # and the final "d" became stuck), then fix it. i = length(s) if r[i] == s[i] for j in 1:i if r[i] != s[j] && r[j] != s[i] r[i], r[j] = r[j], r[i] break end end end   score = sum(x == y for (x, y) in zip(r, s)) return r, score end   for word in ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a") shuffled, score = bestshuffle(word) println("$word: $shuffled ($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.
#Picat
Picat
main =>  % - String assignment S1 = "binary_string", println(s1=S1),    % Picat has re-assignments (:=/2) as well, S1 := "another string", println(s1=S1),    % - String comparison if S1 == "another string" then println(same) else println(not_same) end,    % - String cloning and copying S2 = S1, println(s2=S2),   S3 = copy_term(S1), % for strings it's the same as =/2 println(s3=S3),    % - Check if a string is empty if S3 == "" then println(is_empty) else println(not_empty) end,    % - Append a byte to a string S3 := S3 ++ "s", println(s3=S3),    % - Extract a substring from a string println(substring=S3[5..7]), println(slice=slice(S1,5,7)), println(slice=slice(S1,5)),    % - Replace every occurrence of a byte (or a string) in a string with another string S4 = replace(S3,'s','x'), println(s4=S4),    % - Join strings S5 = S1 ++ " " ++ S2, println(s5=S5),    % using append/4 append(S1," ", S2,S6), println(s6=S6),    % find positions of substrings println(find=findall([From,To],find(S5,"str",From,To))),    % split a string println(split=split(S1," st"))
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.
#PicoLisp
PicoLisp
: (out "rawfile" (mapc wr (range 0 255)) )
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.
#BCPL
BCPL
get "libhdr"   let writebin(x) be $( let f(x) be $( if x>1 then f(x>>1) wrch((x & 1) + '0') $) f(x) wrch('*N') $)   let start() be $( writebin(5) writebin(50) writebin(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.
#Nim
Nim
import bitmap   proc drawLine*(img: Image; p, q: Point; color: Color) = let dx = abs(q.x - p.x) sx = if p.x < q.x: 1 else: -1 dy = abs(q.y - p.y) sy = if p.y < q.y: 1 else: -1   var p = p q = q err = (if dx > dy: dx else: -dy) div 2 e2 = 0   while true: img[p.x, p.y] = color if p == q: break e2 = err if e2 > -dx: err -= dy p.x += sx if e2 < dy: err += dx p.y += sy   when isMainModule: var img = newImage(16, 16) img.fill(White) img.drawLine((0, 7), (7, 15), Black) img.drawLine((7, 15), (15, 7), Black) img.drawLine((15, 7), (7, 0), Black) img.drawLine((7, 0), (0, 7), Black) img.print()
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
#Seed7
Seed7
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
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
#Self
Self
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
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
#SenseTalk
SenseTalk
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
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)..
#Phix
Phix
with javascript_semantics function get225(integer d, string p1, string p2, string p4) string p3 = p1&'-'&lower(p2) p2 &= " by "&lower(p1) p1 &= " by "&lower(p4) if d then return {p1,p3,p2} -- eg {North by east,North-northeast,Northeast by north} else return {p2,p3,p1} -- eg {Northeast by east,East-northeast,East by north} end if end function function get45(sequence res, integer d, string p1, string p2) string p3 res = append(res,p1) -- North/East/South/West if d then p3 = p1&lower(p2) -- Northeast/Southwest else p3 = p2&lower(p1) -- Southeast/Northwest end if res &= get225(1,p1,p3,p2) -- eg get225(1,North,Northeast,East) -- -> {North by east,North-northeast,Northeast by north} res = append(res,p3) -- Northeast/Southeast/Southwest/Northwest res &= get225(0,p2,p3,p1) -- eg get225(0,East,Northeast,North) -- -> {Northeast by east,East-northeast,East by north} return res end function function get90(sequence points) sequence res = {} for i=1 to length(points) do res = get45(res,remainder(i,2),points[i],points[remainder(i,4)+1]) end for -- ie get45(1,North,East) -- get45(0,East,South) -- get45(1,South,West) -- get45(0,West,North) return res end function constant compass_points = get90({"North","East","South","West"}) for i = 1 to 33 do atom test_point = (i-1)*11.25 + 5.62*(remainder(i,3)-1) integer compass_point = remainder(floor(test_point*32/360+0.5),32)+1 printf(1, "%2d  %-22s  %6.2f\n", {compass_point, compass_points[compass_point], test_point}) end for
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() bitdemo(255,2) bitdemo(-15,3) end   procedure bitdemo(i,i2) write() demowrite("i",i) demowrite("i2",i2) demowrite("complement i",icom(i)) demowrite("i or i2",ior(i,i2)) demowrite("i and i2",iand(i,i2)) demowrite("i xor i2",ixor(i,i2)) demowrite("i shift " || i2,ishift(i,i2)) demowrite("i shift -" || i2,ishift(i,-i2)) return end   procedure demowrite(vs,v) return write(vs, ": ", v, " = ", int2bit(v),"b") end
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
img = Image[ConstantArray[{1, 0, 0}, {1000, 1000}]]; img = ReplacePart[img, {1, 1, 1} -> {0, 0, 1}]; ImageValue[img, {1, 1}]
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.
#MATLAB
MATLAB
  %Bitmap class % %Implements a class to manage bitmap images without the need for the %various conversion and display functions % %Available functions: % %fill(obj,color) %setPixel(obj,pixel,color) %getPixel(obj,pixel,[optional: color channel]) %display(obj) %disp(obj) %plot(obj) %image(obj) %save(obj) %open(obj)   classdef Bitmap   %% Public Properties properties   %Channel arrays red; green; blue;   end   %% Public Methods methods   %Creates image and defaults it to black function obj = Bitmap(width,height) obj.red = zeros(height,width,'uint8'); obj.green = zeros(height,width,'uint8'); obj.blue = zeros(height,width,'uint8'); end % End Bitmap Constructor   %Fill the image with a specified color %color = [red green blue] max for each is 255 function fill(obj,color) obj.red(:,:) = color(1); obj.green(:,:) = color(2); obj.blue(:,:) = color(3); assignin('caller',inputname(1),obj); %saves the changes to the object end   %Set a pixel to a specified color %pixel = [x y] %color = [red green blue] function setPixel(obj,pixel,color) obj.red(pixel(2),pixel(1)) = color(1); obj.green(pixel(2),pixel(1)) = color(2); obj.blue(pixel(2),pixel(1)) = color(3); assignin('caller',inputname(1),obj); %saves the changes to the object end   %Get pixel color %pixel = [x y] %varargin can be: % no input for all channels % 'r' or 'red' for red channel % 'g' or 'green' for green channel % 'b' or 'blue' for blue channel function color = getPixel(obj,pixel,varargin)   if( ~isempty(varargin) ) switch (varargin{1}) case {'r','red'} color = obj.red(pixel(2),pixel(1)); case {'g','green'} color = obj.red(pixel(2),pixel(1)); case {'b','blue'} color = obj.red(pixel(2),pixel(1)); end else color = [obj.red(pixel(2),pixel(1)) obj.green(pixel(2),pixel(1)) obj.blue(pixel(2),pixel(1))]; end   end   %Display the image %varargin can be: % no input for all channels % 'r' or 'red' for red channel % 'g' or 'green' for green channel % 'b' or 'blue' for blue channel function display(obj,varargin)   if( ~isempty(varargin) ) switch (varargin{1}) case {'r','red'} image(obj.red) case {'g','green'} image(obj.green) case {'b','blue'} image(obj.blue) end   colormap bone; else bitmap = cat(3,obj.red,obj.green,obj.blue); image(bitmap); end end   %Overload several commonly used display functions function disp(obj,varargin) display(obj,varargin{:}); end   function plot(obj,varargin) display(obj,varargin{:}); end   function image(obj,varargin) display(obj,varargin{:}); end   %Saves the image function save(obj)   %Open file dialogue [fileName,pathName,success] = uiputfile({'*.bmp','Bitmap Image (*.bmp)'},'Save Bitmap As');   if( not(success == 0) ) imwrite(cat(3,obj.red,obj.green,obj.blue),[pathName fileName],'bmp'); %Write image file to disk disp('Save Complete'); end end   %Opens an image and overwrites what is currently stored function success = open(obj)   %Open file dialogue [fileName,pathName,success] = uigetfile({'*.bmp','Bitmap Image (*.bmp)'},'Open Bitmap ');   if( not(success == 0) )   channels = imread([pathName fileName], 'bmp'); %returns color indexed data   %Store each channel obj.red = channels(:,:,1); obj.green = channels(:,:,2); obj.blue = channels(:,:,3);   assignin('caller',inputname(1),obj); %saves the changes to the object success = true; return else success = false; return end end     end %methods end %classdef  
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
#Racket
Racket
#lang racket   (define (build-bell-row previous-row) (define seed (last previous-row)) (reverse (let-values (((reversed _) (for/fold ((acc (list seed)) (prev seed)) ((pprev previous-row)) (let ((n (+ prev pprev))) (values (cons n acc) n))))) reversed)))   (define reverse-bell-triangle (let ((memo (make-hash '((0 . ((1))))))) (λ (rows) (hash-ref! memo rows (λ () (let ((prev (reverse-bell-triangle (sub1 rows)))) (cons (build-bell-row (car prev)) prev)))))))   (define bell-triangle (compose reverse reverse-bell-triangle))   (define bell-number (compose caar reverse-bell-triangle))   (module+ main (map bell-number (range 15)) (bell-number 50) (bell-triangle 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
#Raku
Raku
my @Aitkens-array = lazy [1], -> @b { my @c = @b.tail; @c.push: @b[$_] + @c[$_] for ^@b; @c } ... *;   my @Bell-numbers = @Aitkens-array.map: { .head };   say "First fifteen and fiftieth Bell numbers:"; printf "%2d: %s\n", 1+$_, @Bell-numbers[$_] for flat ^15, 49;   say "\nFirst ten rows of Aitken's array:"; .say for @Aitkens-array[^10];
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 .
#Lua
Lua
actual = {} expected = {} for i = 1, 9 do actual[i] = 0 expected[i] = math.log10(1 + 1 / i) end   n = 0 file = io.open("fibs1000.txt", "r") for line in file:lines() do digit = string.byte(line, 1) - 48 actual[digit] = actual[digit] + 1 n = n + 1 end file:close()   print("digit actual expected") for i = 1, 9 do print(i, actual[i] / n, expected[i]) end
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   +½.
#Java
Java
import org.apache.commons.math3.fraction.BigFraction;   public class BernoulliNumbers {   public static void main(String[] args) { for (int n = 0; n <= 60; n++) { BigFraction b = bernouilli(n); if (!b.equals(BigFraction.ZERO)) System.out.printf("B(%-2d) = %-1s%n", n , b); } }   static BigFraction bernouilli(int n) { BigFraction[] A = new BigFraction[n + 1]; for (int m = 0; m <= n; m++) { A[m] = new BigFraction(1, (m + 1)); for (int j = m; j >= 1; j--) A[j - 1] = (A[j - 1].subtract(A[j])).multiply(new BigFraction(j)); } return A[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.
#CLU
CLU
% Binary search in an array % If the item is found, returns `true' and the index; % if the item is not found, returns `false' and the leftmost insertion point % The datatype must support the < and > operators. binary_search = proc [T: type] (a: array[T], val: T) returns (bool, int) where T has lt: proctype (T,T) returns (bool), T has gt: proctype (T,T) returns (bool) low: int := array[T]$low(a) high: int := array[T]$high(a)   while low <= high do mid: int := low + (high - low) / 2 if a[mid] > val then high := mid - 1 elseif a[mid] < val then low := mid + 1 else return (true, mid) end end return (false, low) end binary_search   % Test the binary search on an array start_up = proc () po: stream := stream$primary_output()    % primes up to 20 (note that arrays are 1-indexed by default) primes: array[int] := array[int]$[2,3,5,7,11,13,17,19]    % binary search for each number from 1 to 20 for n: int in int$from_to(1,20) do i: int found: bool found, i := binary_search[int](primes, n)   if found then stream$putl(po, int$unparse(n) || " found at location " || int$unparse(i)); else stream$putl(po, int$unparse(n) || " not found, would be inserted at location " || int$unparse(i)); end end end start_up
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
#Kotlin
Kotlin
import java.util.Random   object BestShuffle { operator fun invoke(s1: String) : String { val s2 = s1.toCharArray() s2.shuffle() for (i in s2.indices) if (s2[i] == s1[i]) for (j in s2.indices) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { val tmp = s2[i] s2[i] = s2[j] s2[j] = tmp break } return s1 + ' ' + String(s2) + " (" + s2.count(s1) + ')' }   private fun CharArray.shuffle() { val rand = Random() for (i in size - 1 downTo 1) { val r = rand.nextInt(i + 1) val tmp = this[i] this[i] = this[r] this[r] = tmp } }   private fun CharArray.count(s1: String) : Int { var count = 0 for (i in indices) if (s1[i] == this[i]) count++ return count } }   fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }
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.
#PL.2FI
PL/I
  /* PL/I has immediate facilities for all those operations except for */ /* replace. */ s = t; /* assignment */ s = t || u; /* catenation - append one or more bytes. */ if length(s) = 0 then ... /* test for an empty string. */ if s = t then ... /* compare strings. */ u = substr(t, i, j); /* take a substring of t beginning at the */ /* i-th character andcontinuing for j */ /* characters. */ substr(u, i, j) = t; /* replace j characters in u, beginning */ /* with the i-th character. */   /* In string t, replace every occurrence of string u with string v. */ replace: procedure (t, u, v); declare (t, u, v) character (*) varying;   do until (k = 0); k = index(t, u); if k > 0 then t = substr(t, 1, k-1) || v || substr(t, k+length(u)); end; end replace;  
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.
#PowerShell
PowerShell
  Clear-Host   ## String creation (which is string assignment): Write-Host "`nString creation (which is string assignment):" -ForegroundColor Cyan Write-Host '[string]$s = "Hello cruel world"' -ForegroundColor Yellow [string]$s = "Hello cruel world"   ## String (or any variable) destruction: Write-Host "`nString (or any variable) destruction:" -ForegroundColor Cyan Write-Host 'Remove-Variable -Name s -Force' -ForegroundColor Yellow Remove-Variable -Name s -Force   ## Now reassign the variable: Write-Host "`nNow reassign the variable:" -ForegroundColor Cyan Write-Host '[string]$s = "Hello cruel world"' -ForegroundColor Yellow [string]$s = "Hello cruel world"   Write-Host "`nString comparison -- default is case insensitive:" -ForegroundColor Cyan Write-Host '$s -eq "HELLO CRUEL WORLD"' -ForegroundColor Yellow $s -eq "HELLO CRUEL WORLD" Write-Host '$s -match "HELLO CRUEL WORLD"' -ForegroundColor Yellow $s -match "HELLO CRUEL WORLD" Write-Host '$s -cmatch "HELLO CRUEL WORLD"' -ForegroundColor Yellow $s -cmatch "HELLO CRUEL WORLD"   ## Copy a string: Write-Host "`nCopy a string:" -ForegroundColor Cyan Write-Host '$t = $s' -ForegroundColor Yellow $t = $s   ## Check if a string is empty: Write-Host "`nCheck if a string is empty:" -ForegroundColor Cyan Write-Host 'if ($s -eq "") {"String is empty."} else {"String = $s"}' -ForegroundColor Yellow if ($s -eq "") {"String is empty."} else {"String = $s"}   ## Append a byte to a string: Write-Host "`nAppend a byte to a string:" -ForegroundColor Cyan Write-Host "`$s += [char]46`n`$s" -ForegroundColor Yellow $s += [char]46 $s   ## Extract (and display) substring from a string: Write-Host "`nExtract (and display) substring from a string:" -ForegroundColor Cyan Write-Host '"Is the world $($s.Substring($s.IndexOf("c"),5))?"' -ForegroundColor Yellow "Is the world $($s.Substring($s.IndexOf("c"),5))?"   ## Replace every occurrence of a byte (or a string) in a string with another string: Write-Host "`nReplace every occurrence of a byte (or a string) in a string with another string:" -ForegroundColor Cyan Write-Host "`$t = `$s -replace `"cruel`", `"beautiful`"`n`$t" -ForegroundColor Yellow $t = $s -replace "cruel", "beautiful" $t   ## Join strings: Write-Host "`nJoin strings [1]:" -ForegroundColor Cyan Write-Host '"Is the world $($s.Split()[1]) or $($t.Split()[1])?"' -ForegroundColor Yellow "Is the world $($s.Split()[1]) or $($t.Split()[1])?" Write-Host "`nJoin strings [2]:" -ForegroundColor Cyan Write-Host '"{0} or {1}... I don''t care." -f (Get-Culture).TextInfo.ToTitleCase($s.Split()[1]), $t.Split()[1]' -ForegroundColor Yellow "{0} or {1}... I don't care." -f (Get-Culture).TextInfo.ToTitleCase($s.Split()[1]), $t.Split()[1] Write-Host "`nJoin strings [3] (display an integer array using the -join operater):" -ForegroundColor Cyan Write-Host '1..12 -join ", "' -ForegroundColor Yellow 1..12 -join ", "   ## Display an integer array in a tablular format: Write-Host "`nMore string madness... display an integer array in a tablular format:" -ForegroundColor Cyan Write-Host '1..12 | Format-Wide {$_.ToString().PadLeft(2)}-Column 3 -Force' -NoNewline -ForegroundColor Yellow 1..12 | Format-Wide {$_.ToString().PadLeft(2)} -Column 3 -Force  
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.
#Beads
Beads
beads 1 program 'Binary Digits' calc main_init loop across:[5, 50, 9000] val:v log to_str(v, base:2)
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.
#OCaml
OCaml
let draw_line ~img ~color ~p0:(x0,y0) ~p1:(x1,y1) =   let steep = abs(y1 - y0) > abs(x1 - x0) in   let plot = if steep then (fun x y -> put_pixel img color y x) else (fun x y -> put_pixel img color x y) in   let x0, y0, x1, y1 = if steep then y0, x0, y1, x1 else x0, y0, x1, y1 in let x0, x1, y0, y1 = if x0 > x1 then x1, x0, y1, y0 else x0, x1, y0, y1 in   let delta_x = x1 - x0 and delta_y = abs(y1 - y0) in let error = -delta_x / 2 and y_step = if y0 < y1 then 1 else -1 in let rec loop x y error = plot x y; if x <= x1 then let error = error + delta_y in let y, error = if error > 0 then (y + y_step), (error - delta_x) else y, error in loop (succ x) y error in loop x0 y0 error ;;
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
#Sidef
Sidef
var t = true; var f = 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
#Simula
Simula
$!/?\=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
#Slate
Slate
$!/?\=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)..
#Picat
Picat
go => Names = ["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" ], foreach(I in 0..32) J = I mod 32, D = I * 11.25, if I mod 3 == 1 then D := D + 5.62 end, if I mod 3 == 2 then D := D - 5.62 end, printf("%2d %-20s %6.2f\n", J+1, Names[J+1], D) end, nl.
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.
#Inform_6
Inform 6
[ bitwise a b temp; print "a and b: ", a & b, "^"; print "a or b: ", a | b, "^"; print "not a: ", ~a, "^"; @art_shift a b -> temp; print "a << b (arithmetic): ", temp, "^"; temp = -b; @art_shift a temp -> temp; print "a >> b (arithmetic): ", temp, "^"; @log_shift a b -> temp; print "a << b (logical): ", temp, "^"; temp = -b; @log_shift a temp -> temp; print "a >> b (logical): ", temp, "^"; ];  
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.
#MAXScript
MAXScript
local myBitmap = bitmap 512 512
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.
#Modula-3
Modula-3
INTERFACE Bitmap;   TYPE UByte = BITS 8 FOR [0 .. 16_FF]; Pixel = RECORD R, G, B: UByte; END; Point = RECORD x, y: UByte; END; T = REF ARRAY OF ARRAY OF Pixel;   CONST Black = Pixel{0, 0, 0}; White = Pixel{255, 255, 255}; Red = Pixel{255, 0, 0}; Green = Pixel{0, 255, 0}; Blue = Pixel{0, 0, 255}; Yellow = Pixel{255, 255, 0};   EXCEPTION BadImage; BadColor;   PROCEDURE NewImage(height, width: UByte): T RAISES {BadImage}; PROCEDURE Fill(VAR pic: T; color: Pixel); PROCEDURE GetPixel(VAR pic: T; point: Point): Pixel RAISES {BadColor}; PROCEDURE SetPixel(VAR pic: T; point: Point; color: Pixel);   END Bitmap.
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
#REXX
REXX
/*REXX program calculates and displays a range of Bell numbers (index starts at zero).*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' & HI=="" then do; LO=0; HI=14; end /*Not specified? Then use the default.*/ if LO=='' | LO=="," then LO= 0 /* " " " " " " */ if HI=='' | HI=="," then HI= 15 /* " " " " " " */ numeric digits max(9, HI*2) /*crudely calculate the # decimal digs.*/ !.=.;  !.0= 1;  !.1= 1; @.= 1 /*the FACT function uses memoization.*/ do j=0 for HI+1; $= j==0; jm= j-1 /*JM is used for a shortcut (below). */ do k=0 for j; _= jm - k /* [↓] calculate a Bell # the easy way*/ $= $ + comb(jm, k) * @._ /*COMB≡combination or binomial function*/ end /*k*/ @.j= $ /*assign the Jth Bell number to @ array*/ if j>=LO & j<=HI then say ' Bell('right(j, length(HI) )") = " commas($) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do c=length(_)-3 to 1 by -3; _=insert(',', _, c); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ comb: procedure expose !.; parse arg x,y; if x==y then return 1 if x-y<y then y= x - y; if !.x.y\==. then return !.x.y / fact(y) _= 1; do j=x-y+1 to x; _= _*j; end;  !.x.y= _; return _ / fact(y) /*──────────────────────────────────────────────────────────────────────────────────────*/ fact: procedure expose !.; parse arg x; if !.x\==. then return !.x;  != 1 do f=2 for x-1;  != ! * f; end;  !.x= !; return !
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 .
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
fibdata = Array[First@IntegerDigits@Fibonacci@# &, 1000]; Table[{d, N@Count[fibdata, d]/Length@fibdata, Log10[1. + 1/d]}, {d, 1, 9}] // Grid
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 .
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method brenfordDeveation(nlist = Rexx[]) public static observed = 0 loop n_ over nlist d1 = n_.left(1) if d1 = 0 then iterate n_ observed[d1] = observed[d1] + 1 end n_ say ' '.right(4) 'Observed'.right(11) 'Expected'.right(11) 'Deviation'.right(11) loop n_ = 1 to 9 actual = (observed[n_] / (nlist.length - 1)) expect = Rexx(Math.log10(1 + 1 / n_)) deviat = expect - actual say n_.right(3)':' (actual * 100).format(3, 6)'%' (expect * 100).format(3, 6)'%' (deviat * 100).abs().format(3, 6)'%' end n_ return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method fibonacciList(size = 1000) public static returns Rexx[] fibs = Rexx[size + 1] fibs[0] = 0 fibs[1] = 1 loop n_ = 2 to size fibs[n_] = fibs[n_ - 1] + fibs[n_ - 2] end n_ return fibs   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg n_ . if n_ = '' then n_ = 1000 fibList = fibonacciList(n_) say 'Fibonacci sequence to' n_ brenfordDeveation(fibList) return  
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   +½.
#jq
jq
# def negate: # def lessOrEqual(x; y): # x <= y # def long_add(x;y): # x+y # def long_minus(x;y): # x-y # def long_multiply(x;y) # x*y # def long_divide(x;y): # x/y => [q,r] # def long_div(x;y) # integer division # def long_mod(x;y) # %   # In all cases, x and y must be strings   def negate: (- tonumber) | tostring;   def lessOrEqual(num1; num2): (num1|tonumber) <= (num2|tonumber);   def long_add(num1; num2): ((num1|tonumber) + (num2|tonumber)) | tostring;   def long_minus(x;y): ((num1|tonumber) - (num2|tonumber)) | tostring;   # multiply two decimal strings, which may be signed (+ or -) def long_multiply(num1; num2): ((num1|tonumber) * (num2|tonumber)) | tostring;   # return [quotient, remainder] # 0/0 = 1; n/0 => error def long_divide(xx;yy): # x/y => [q,r] imples x == (y * q) + r def ld(x;y): def abs: if . < 0 then -. else . end; (x|abs) as $x | (y|abs) as $y | (if (x >= 0 and y > 0) or (x < 0 and y < 0) then 1 else -1 end) as $sign | (if x >= 0 then 1 else -1 end) as $sx | [$sign * ($x / $y | floor), $sx * ($x % $y)]; ld( xx|tonumber; yy|tonumber) | map(tostring);   def long_div(x;y): long_divide(x;y) | .[0];   def long_mod(x;y): ((x|tonumber) % (y|tonumber)) | tostring;
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.
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. binary-search.   DATA DIVISION. WORKING-STORAGE SECTION. 01 nums-area VALUE "01040612184356". 03 nums PIC 9(2) OCCURS 7 TIMES ASCENDING KEY nums INDEXED BY nums-idx. PROCEDURE DIVISION. SEARCH ALL nums WHEN nums (nums-idx) = 4 DISPLAY "Found 4 at index " nums-idx END-SEARCH . END PROGRAM binary-search.
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
#Liberty_BASIC
Liberty BASIC
'see Run BASIC solution list$ = "abracadabra seesaw pop grrrrrr up a"   while word$(list$,ii + 1," ") <> "" ii = ii + 1 w$ = word$(list$,ii," ") bs$ = bestShuffle$(w$) count = 0 for i = 1 to len(w$) if mid$(w$,i,1) = mid$(bs$,i,1) then count = count + 1 next i print w$;" ";bs$;" ";count wend   function bestShuffle$(s1$) s2$ = s1$ for i = 1 to len(s2$) for j = 1 to len(s2$) if (i <> j) and (mid$(s2$,i,1) <> mid$(s1$,j,1)) and (mid$(s2$,j,1) <> mid$(s1$,i,1)) then if j < i then i1 = j:j1 = i else i1 = i:j1 = j s2$ = left$(s2$,i1-1) + mid$(s2$,j1,1) + mid$(s2$,i1+1,(j1-i1)-1) + mid$(s2$,i1,1) + mid$(s2$,j1+1) end if next j next i bestShuffle$ = s2$ end function
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.
#Prolog
Prolog
% Create a string (no destruction necessary) ?- X = "a test string". X = "a test string".   % String assignment, there is no assignment but you can unify between variables, also 'String cloning and copying' ?- X = "a test string", X = Y. X = Y, Y = "a test string".   % String comparison ?- X = "a test string", Y = "a test string", X = Y. X = Y, Y = "a test string".   ?- X = "a test string", Y = "a different string", X = Y. false.   % Test for empty string, this is the same as string comparison. ?- X = "a test string", Y = "", X = Y. false.   ?- X = "", Y = "", X = Y. false.   % Append a byte to a string ?- X = "a test string", string_concat(X, "!", Y). X = "a test string", Y = "a test string!".   % Extract a substring from a string ?- X = "a test string", sub_string(X, 2, 4, _, Y). X = "a test string", Y = "test".   ?- X = "a test string", sub_string(X, Before, Len, After, test). X = "a test string", Before = 2, Len = 4, After = 7 ; false.   % Replace every occurrence of a byte (or a string) in a string with another string ?- X = "a test string", re_replace('t'/g, 'o', X, Y). X = "a test string", Y = "a oeso soring".   % Join strings ?- X = "a test string", Y = " with extra!", string_concat(X, Y, Z). X = "a test string", Y = " with extra!", Z = "a test string with extra!".  
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.
#Befunge
Befunge
&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@
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.
#Pascal
Pascal
#! /usr/bin/perl use strict; use Image::Imlib2;   sub my_draw_line { my ( $img, $x0, $y0, $x1, $y1) = @_;   my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { ( $y0, $x0 ) = ( $x0, $y0); ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { ( $x1, $x0 ) = ( $x0, $x1 ); ( $y1, $y0 ) = ( $y0, $y1 ); } my $deltax = $x1 - $x0; my $deltay = abs($y1 - $y0); my $error = $deltax / 2; my $ystep; my $y = $y0; my $x; $ystep = ( $y0 < $y1 ) ? 1 : -1; for( $x = $x0; $x <= $x1; $x += 1 ) { if ( $steep ) { $img->draw_point($y, $x); } else { $img->draw_point($x, $y); } $error -= $deltay; if ( $error < 0 ) { $y += $ystep; $error += $deltax; } } }   # test my $img = Image::Imlib2->new(160, 160); $img->set_color(255, 255, 255, 255); # white $img->fill_rectangle(0,0,160,160);   $img->set_color(0,0,0,255); # black my_draw_line($img, 10, 80, 80, 160); my_draw_line($img, 80, 160, 160, 80); my_draw_line($img, 160, 80, 80, 10); my_draw_line($img, 80, 10, 10, 80);   $img->save("test0.png");   # let's try the same using its internal algo $img->set_color(255, 255, 255, 255); # white $img->fill_rectangle(0,0,160,160); $img->set_color(0,0,0,255); # black $img->draw_line(10, 80, 80, 160); $img->draw_line(80, 160, 160, 80); $img->draw_line(160, 80, 80, 10); $img->draw_line(80, 10, 10, 80);   $img->save("test1.png");   exit 0;
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
#Smalltalk
Smalltalk
$!/?\=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
#SNUSP
SNUSP
$!/?\=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
#SPL
SPL
datatype 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)..
#PicoLisp
PicoLisp
(scl 3)   (setq *Compass # Build lookup table (let H -16.875 (mapcar '((Str) (cons (inc 'H 11.25) # Heading in degrees (pack # Compass point (replace (chop Str) "N" "north" "E" "east" "S" "south" "W" "west" "b" " by " ) ) ) ) '("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" ) ) ) )   (de heading (Deg) (rank (% Deg 360.00) *Compass) )   (for I (range 0 32) (let H (* I 11.25) (case (% I 3) (1 (inc 'H 5.62)) (2 (dec 'H 5.62)) ) (tab (3 1 -18 8) (inc (% I 32)) NIL (cdr (heading H)) (round H 2) ) ) )
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.
#J
J
bAND=: 17 b. NB. 16+#.0 0 0 1 bOR=: 23 b. NB. 16+#.0 1 1 1 bXOR=: 22 b. NB. 16+#.0 1 1 0 b1NOT=: 28 b. NB. 16+#.1 1 0 0 bLshift=: 33 b.~ NB. see http://www.jsoftware.com/help/release/bdot.htm bRshift=: 33 b.~ - bRAshift=: 34 b.~ - bLrot=: 32 b.~ bRrot=: 32 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.
#Nim
Nim
type Luminance* = uint8 Index* = int   Color* = tuple r, g, b: Luminance   Image* = ref object w*, h*: Index pixels*: seq[Color]   Point* = tuple x, y: Index   proc color*(r, g, b: SomeInteger): Color = ## Build a color value from R, G and B values. result.r = r.uint8 result.g = g.uint8 result.b = b.uint8   const Black* = color( 0, 0, 0) White* = color(255, 255, 255)   proc newImage*(width, height: int): Image = ## Create an image with given width and height. new(result) result.w = width result.h = height result.pixels.setLen(width * height)   iterator indices*(img: Image): Point = ## Yield the pixels coordinates as tuples. for y in 0 ..< img.h: for x in 0 ..< img.w: yield (x, y)   proc `[]`*(img: Image; x, y: int): Color = ## Get a pixel RGB value. img.pixels[y * img.w + x]   proc `[]=`*(img: Image; x, y: int; c: Color) = ## Set a pixel RGB value to given color. img.pixels[y * img.w + x] = c   proc fill*(img: Image; color: Color) = ## Fill the image with a color. for x, y in img.indices: img[x, y] = color   proc print*(img: Image) = ## Output an ASCII representation of the image. for x, y in img.indices: if x mod img.w == 0: stdout.write '\n' stdout.write if img[x, y] == White: '.' else: 'H' stdout.write '\n'   when isMainModule: var img = newImage(100, 20) img.fill color(255, 255, 255) img[1, 2] = color(255, 0, 0) img[3, 4] = img[1, 2] img.print
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.
#OCaml
OCaml
let new_img ~width ~height = let all_channels = let kind = Bigarray.int8_unsigned and layout = Bigarray.c_layout in Bigarray.Array3.create kind layout 3 width height in let r_channel = Bigarray.Array3.slice_left_2 all_channels 0 and g_channel = Bigarray.Array3.slice_left_2 all_channels 1 and b_channel = Bigarray.Array3.slice_left_2 all_channels 2 in (all_channels, r_channel, g_channel, b_channel)
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
#Ruby
Ruby
def bellTriangle(n) tri = Array.new(n) for i in 0 .. n - 1 do tri[i] = Array.new(i) for j in 0 .. i - 1 do tri[i][j] = 0 end end tri[1][0] = 1 for i in 2 .. n - 1 do tri[i][0] = tri[i - 1][i - 2] for j in 1 .. i - 1 do tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] end end return tri end   def main bt = bellTriangle(51) puts "First fifteen and fiftieth Bell numbers:" for i in 1 .. 15 do puts "%2d: %d" % [i, bt[i][0]] end puts "50: %d" % [bt[50][0]] puts   puts "The first ten rows of Bell's triangle:" for i in 1 .. 10 do puts bt[i].inspect end end   main()
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 .
#Nim
Nim
import math import strformat   type   # Non zero digit range. Digit = range[1..9]   # Count array used to compute a distribution. Count = array[Digit, Natural]   # Array to store frequencies. Distribution = array[Digit, float]     #################################################################################################### # Fibonacci numbers generation.   import bignum   proc fib(count: int): seq[Int] = ## Build a sequence of "count auccessive Finonacci numbers. result.setLen(count) result[0..1] = @[newInt(1), newInt(1)] for i in 2..<count: result[i] = result[i-1] + result[i-2]     #################################################################################################### # Benford distribution.   proc benfordDistrib(): Distribution = ## Compute Benford distribution.   for d in 1..9: result[d] = log10(1 + 1 / d)   const BenfordDist = benfordDistrib()   #---------------------------------------------------------------------------------------------------   template firstDigit(n: Int): Digit = # Return the first (non null) digit of "n". ord(($n)[0]) - ord('0')   #---------------------------------------------------------------------------------------------------   proc actualDistrib(s: openArray[Int]): Distribution = ## Compute actual distribution of first digit. ## Null values are ignored.   var counts: Count for val in s: if not val.isZero(): inc counts[val.firstDigit()]   let total = sum(counts) for d in 1..9: result[d] = counts[d] / total   #---------------------------------------------------------------------------------------------------   proc display(distrib: Distribution) = ## Display an actual distribution versus the Benford reference distribution.   echo "d actual expected" echo "---------------------" for d in 1..9: echo fmt"{d} {distrib[d]:6.4f} {BenfordDist[d]:6.4f}"     #———————————————————————————————————————————————————————————————————————————————————————————————————   let fibSeq = fib(1000) let distrib = actualDistrib(fibSeq) echo "Fibonacci numbers first digit distribution:\n" distrib.display()
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 .
#Oberon-2
Oberon-2
  MODULE BenfordLaw; IMPORT LRealStr, LRealMath, Out := NPCT:Console;   VAR r: ARRAY 1000 OF LONGREAL; d: ARRAY 10 OF LONGINT; a: LONGREAL; i: LONGINT;   PROCEDURE Fibb(VAR r: ARRAY OF LONGREAL); VAR i: LONGINT; BEGIN r[0] := 1.0;r[1] := 1.0; FOR i := 2 TO LEN(r) - 1 DO r[i] := r[i - 2] + r[i - 1] END END Fibb;   PROCEDURE Dist(r [NO_COPY]: ARRAY OF LONGREAL; VAR d: ARRAY OF LONGINT); VAR i: LONGINT; str: ARRAY 256 OF CHAR; BEGIN FOR i := 0 TO LEN(r) - 1 DO LRealStr.RealToStr(r[i],str); INC(d[ORD(str[0]) - ORD('0')]) END END Dist;   BEGIN Fibb(r); Dist(r,d); Out.String("First 1000 fibonacci numbers: ");Out.Ln; Out.String(" digit ");Out.String(" observed ");Out.String(" predicted ");Out.Ln; FOR i := 1 TO LEN(d) - 1 DO a := LRealMath.ln(1.0 + 1.0 / i ) / LRealMath.ln(10); Out.Int(i,5);Out.LongRealFix(d[i] / 1000.0,9,3);Out.LongRealFix(a,10,3);Out.Ln END END BenfordLaw.  
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   +½.
#Julia
Julia
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for m = 0 : n A[m + 1] = 1 // (m + 1) for j = m : -1 : 1 A[j] = j * (A[j] - A[j + 1]) end end return A[1] end   function display(n) B = map(bernoulli, 0 : n) pad = mapreduce(x -> ndigits(numerator(x)) + Int(x < 0), max, B) argdigits = ndigits(n) for i = 0 : n if numerator(B[i + 1]) & 1 == 1 println( "B(", lpad(i, argdigits), ") = ", lpad(numerator(B[i + 1]), pad), " / ", denominator(B[i + 1]) ) end end end   display(60)   # Alternative: Following the comment in the Perl section it is much more efficient # to compute the list of numbers instead of one number after the other.   function BernoulliList(len) A = Vector{Rational{BigInt}}(undef, len + 1) B = similar(A) for n in 0 : len A[n + 1] = 1 // (n + 1) for j = n : -1 : 1 A[j] = j * (A[j] - A[j + 1]) end B[n + 1] = A[1] end return B end   for (n, b) in enumerate(BernoulliList(60)) isodd(numerator(b)) && println("B($(n-1)) = $b") 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.
#CoffeeScript
CoffeeScript
binarySearch = (xs, x) -> do recurse = (low = 0, high = xs.length - 1) -> mid = Math.floor (low + high) / 2 switch when high < low then NaN when xs[mid] > x then recurse low, mid - 1 when xs[mid] < x then recurse mid + 1, high else mid
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
#Lua
Lua
math.randomseed(os.time())   local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end   local function bestshuffle(s, r) local order, shufl, count = {}, {}, 0 for ch in s:gmatch(".") do order[#order+1], shufl[#shufl+1] = ch, ch end if r then shuffle(shufl) end for i = 1, #shufl do for j = 1, #shufl do if i ~= j and shufl[i] ~= order[j] and shufl[j] ~= order[i] then shufl[i], shufl[j] = shufl[j], shufl[i] end end end for i = 1, #shufl do if shufl[i] == order[i] then count = count + 1 end end return table.concat(shufl), count end   local words = { "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }   local function test(r) print(r and "RANDOM:" or "DETERMINISTIC:") for _, word in ipairs(words) do local shufl, count = bestshuffle(word, r) print(string.format("%s, %s, (%d)", word, shufl, count)) end print() end   test(true) test(false)
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.
#PureBasic
PureBasic
  ;string creation x$ = "hello world"   ;string destruction x$ = ""   ;string comparison If x$ = "hello world" : PrintN("String is equal") : EndIf   ;string copying; y$ = x$   ; check If empty If x$ = "" : PrintN("String is empty") : EndIf   ; append a byte x$ = x$ + Chr(41)   ; extract a substring x$ = Mid(x$, 1, 5)   ; replace bytes x$ = ReplaceString(x$, "world", "earth")   ; join strings x$ = "hel" + "lo w" + "orld"  
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.
#BQN
BQN
Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}   Bin¨5‿50‿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.
#Perl
Perl
#! /usr/bin/perl use strict; use Image::Imlib2;   sub my_draw_line { my ( $img, $x0, $y0, $x1, $y1) = @_;   my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { ( $y0, $x0 ) = ( $x0, $y0); ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { ( $x1, $x0 ) = ( $x0, $x1 ); ( $y1, $y0 ) = ( $y0, $y1 ); } my $deltax = $x1 - $x0; my $deltay = abs($y1 - $y0); my $error = $deltax / 2; my $ystep; my $y = $y0; my $x; $ystep = ( $y0 < $y1 ) ? 1 : -1; for( $x = $x0; $x <= $x1; $x += 1 ) { if ( $steep ) { $img->draw_point($y, $x); } else { $img->draw_point($x, $y); } $error -= $deltay; if ( $error < 0 ) { $y += $ystep; $error += $deltax; } } }   # test my $img = Image::Imlib2->new(160, 160); $img->set_color(255, 255, 255, 255); # white $img->fill_rectangle(0,0,160,160);   $img->set_color(0,0,0,255); # black my_draw_line($img, 10, 80, 80, 160); my_draw_line($img, 80, 160, 160, 80); my_draw_line($img, 160, 80, 80, 10); my_draw_line($img, 80, 10, 10, 80);   $img->save("test0.png");   # let's try the same using its internal algo $img->set_color(255, 255, 255, 255); # white $img->fill_rectangle(0,0,160,160); $img->set_color(0,0,0,255); # black $img->draw_line(10, 80, 80, 160); $img->draw_line(80, 160, 160, 80); $img->draw_line(160, 80, 80, 10); $img->draw_line(80, 10, 10, 80);   $img->save("test1.png");   exit 0;
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
#Standard_ML
Standard ML
datatype 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
#Stata
Stata
% if {""} then {puts true} else {puts false} expected boolean value but got ""
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)..
#PowerShell
PowerShell
function Convert-DegreeToDirection ( [double]$Degree ) {   $Directions = @( 'n','n by e','n-ne','ne by n','ne','ne by e','e-ne','e by n', 'e','e by s','e-se','se by e','se','se by s','s-se','s by e', 's','s by w','s-sw','sw by s','sw','sw by w','w-sw','w by s', 'w','w by n','w-nw','nw by w','nw','nw by n','n-nw','n by w', 'n' ).Replace( 's', 'south' ).Replace( 'e', 'east' ).Replace( 'n', 'north' ).Replace( 'w', 'west' )   $Directions[[math]::floor(( $Degree % 360 ) / 11.25 + 0.5 )] }   $x = 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   $x | % { Convert-DegreeToDirection -Degree $_ }
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.
#Java
Java
public static void bitwise(int a, int b){ System.out.println("a AND b: " + (a & b)); System.out.println("a OR b: "+ (a | b)); System.out.println("a XOR b: "+ (a ^ b)); System.out.println("NOT a: " + ~a); System.out.println("a << b: " + (a << b)); // left shift System.out.println("a >> b: " + (a >> b)); // arithmetic right shift System.out.println("a >>> b: " + (a >>> b)); // logical right shift System.out.println("a rol b: " + Integer.rotateLeft(a, b)); //rotate left, Java 1.5+ System.out.println("a ror b: " + Integer.rotateRight(a, b)); //rotate right, Java 1.5+ }
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.
#Octave
Octave
im = zeros(W, H, 3, "uint8"); % create an RGB image of width W and height H % and intensity from 0 to 255; black (all zeros) im(:,:,1) = 255; % set R to 255 im(:,:,2) = 100; % set G to 100 im(:,:,3) = 155; % set B to 155 im(floor(W/2), floor(H/2), :) = 0; % pixel in the center made black disp(im(floor(W/3), floor(H/3), :)) % display intensities of the pixel % at W/3, H/3 p = im(40,40,:); % or just store it in the vector p, so that % p(1) is R, p(2) G and p(3) is B
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
#Rust
Rust
use num::BigUint;   fn main() { let bt = bell_triangle(51); // the fifteen first for i in 1..=15 { println!("{}: {}", i, bt[i][0]); }   // the fiftieth println!("50: {}", bt[50][0]) }   fn bell_triangle(n: usize) -> Vec<Vec<BigUint>> { let mut tri: Vec<Vec<BigUint>> = Vec::with_capacity(n); for i in 0..n { let v = vec![BigUint::from(0u32); i]; tri.push(v); } tri[1][0] = BigUint::from(1u32);   for i in 2..n { tri[i][0] = BigUint::from_bytes_be(&tri[i - 1][i - 2].to_bytes_be()); for j in 1..i { let added_big_uint = &tri[i][j - 1] + &tri[i - 1][j - 1]; tri[i][j] = BigUint::from_bytes_be(&added_big_uint.to_bytes_be()); } }   tri }  
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
#Scala
Scala
import scala.collection.mutable.ListBuffer   object BellNumbers { class BellTriangle { val arr: ListBuffer[Int] = ListBuffer.empty[Int]   def this(n: Int) { this()   val length = n * (n + 1) / 2 for (_ <- 0 until length) { arr += 0 }   this (1, 0) = 1 for (i <- 2 to n) { this (i, 0) = this (i - 1, i - 2) for (j <- 1 until i) { this (i, j) = this (i, j - 1) + this (i - 1, j - 1) } } }   private def index(row: Int, col: Int): Int = { require(row > 0, "row must be greater than zero") require(col >= 0, "col must not be negative") require(col < row, "col must be less than row")   row * (row - 1) / 2 + col }   def apply(row: Int, col: Int): Int = { val i = index(row, col) arr(i) }   def update(row: Int, col: Int, value: Int): Unit = { val i = index(row, col) arr(i) = value } }   def main(args: Array[String]): Unit = { val rows = 15 val bt = new BellTriangle(rows)   println("First fifteen Bell numbers:") for (i <- 0 until rows) { printf("%2d: %d\n", i + 1, bt(i + 1, 0)) }   for (i <- 1 to 10) { print(bt(i, 0)) for (j <- 1 until i) { print(s", ${bt(i, j)}") } 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 .
#OCaml
OCaml
  open Num   let fib = let rec fib_aux f0 f1 = function | 0 -> f0 | 1 -> f1 | n -> fib_aux f1 (f1 +/ f0) (n - 1) in fib_aux (num_of_int 0) (num_of_int 1) ;;   let create_fibo_string = function n -> string_of_num (fib n) ;; let rec range i j = if i > j then [] else i :: (range (i + 1) j)   let n_max = 1000 ;;   let numbers = range 1 n_max in let get_first_digit = function s -> Char.escaped (String.get s 0) in let first_digits = List.map get_first_digit (List.map create_fibo_string numbers) in let data = Array.create 9 0 in let fill_data vec = function n -> vec.(n - 1) <- vec.(n - 1) + 1 in List.iter (fill_data data) (List.map int_of_string first_digits) ; Printf.printf "\nFrequency of the first digits in the Fibonacci sequence:\n" ; Array.iter (Printf.printf "%f ") (Array.map (fun x -> (float x) /. float (n_max)) data) ;   let xvalues = range 1 9 in let benfords_law = function x -> log10 (1.0 +. 1.0 /. float (x)) in Printf.printf "\nPrediction of Benford's law:\n " ; List.iter (Printf.printf "%f ") (List.map benfords_law xvalues) ; Printf.printf "\n" ;;  
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   +½.
#Kotlin
Kotlin
import org.apache.commons.math3.fraction.BigFraction   object Bernoulli { operator fun invoke(n: Int) : BigFraction { val A = Array(n + 1, init) for (m in 0..n) for (j in m downTo 1) A[j - 1] = A[j - 1].subtract(A[j]).multiply(integers[j]) return A.first() }   val max = 60   private val init = { m: Int -> BigFraction(1, m + 1) } private val integers = Array(max + 1, { m: Int -> BigFraction(m) } ) }   fun main(args: Array<String>) { for (n in 0..Bernoulli.max) if (n % 2 == 0 || n == 1) System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n)) }
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.
#Common_Lisp
Common Lisp
(defun binary-search (value array) (let ((low 0) (high (1- (length array))))   (do () ((< high low) nil) (let ((middle (floor (+ low high) 2)))   (cond ((> (aref array middle) value) (setf high (1- middle)))   ((< (aref array middle) value) (setf low (1+ middle)))   (t (return middle)))))))
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
BestShuffle[data_] := Flatten[{data,First[SortBy[ List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]   Print[#[[1]], "," #[[2]], ",(", #[[3]], ")"] & /@ BestShuffle /@ {"abracadabra","seesaw","elk","grrrrrr","up","a"}  
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
#Nim
Nim
import times import sequtils import strutils import random   proc count(s1, s2: string): int = for i, c in s1: if c == s2[i]: result.inc   proc shuffle(str: string): string = var r = initRand(getTime().toUnix()) var chrs = toSeq(str.items) for i in 0 ..< chrs.len: let chosen = r.rand(chrs.len-1) swap(chrs[i], chrs[chosen]) return chrs.join("")   proc bestShuffle(str: string): string = var chrs = toSeq(shuffle(str).items) for i in chrs.low .. chrs.high: if chrs[i] != str[i]: continue for j in chrs.low .. chrs.high: if chrs[i] != chrs[j] and chrs[i] != str[j] and chrs[j] != str[i]: swap(chrs[i], chrs[j]) break return chrs.join("")   when isMainModule: let words = @["abracadabra", "seesaw", "grrrrrr", "pop", "up", "a", "antidisestablishmentarianism"]; for w in words: let shuffled = bestShuffle(w) echo "$1 $2 $3" % [w, shuffled, $count(w, shuffled)]  
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.
#Python
Python
s1 = "A 'string' literal \n" s2 = 'You may use any of \' or " as delimiter' s3 = """This text goes over several lines up to the closing triple quote"""
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.
#Racket
Racket
  #lang racket   ;; Byte strings can be created either by a function (b1) ;; or as a literal string (b2). No operation is needed for ;; destruction due to garbage collection.   (define b1 (make-bytes 5 65))  ; b1 -> #"AAAAA" (define b2 #"BBBBB")  ; b2 -> #"BBBBB"   ;; String assignment. Note that b2 cannot be ;; mutated since literal byte strings are immutable.   (bytes-set! b1 0 66)  ; b1 -> #"BAAAA"   ;; Comparison. Less than & greater than are ;; lexicographic comparison.   (bytes=? b1 b2)  ; -> #f (bytes<? b1 b2)  ; -> #t (bytes>? b1 b2)  ; -> #f   ;; Byte strings can be cloned by copying to a ;; new one or by overwriting an existing one.   (define b3 (bytes-copy b1))  ; b3 -> #"BAAAA" (bytes-copy! b1 0 b2)  ; b1 -> #"BBBBB"   ;; Byte strings can be appended to one another. A ;; single byte is appended as a length 1 string.   (bytes-append b1 b2)  ; -> #"BBBBBBBBBB" (bytes-append b3 #"B")  ; -> #"BAAAAB"   ;; Substring   (subbytes b3 0)  ; -> #"BAAAA" (subbytes b3 0 2)  ; -> #"BA"   ;; Regular expressions can be used to do replacements ;; in a byte string (or ordinary strings)   (regexp-replace #"B" b1 #"A")  ; -> #"ABBBB" (only the first one) (regexp-replace* #"B" b1 #"A") ; -> #"AAAAA"   ;; Joining strings   (bytes-join (list b2 b3) #" ") ; -> #"BBBBB BAAAA"  
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.
#Bracmat
Bracmat
( dec2bin = bit bits .  :?bits & whl ' ( !arg:>0 & mod$(!arg,2):?bit & div$(!arg,2):?arg & !bit !bits:?bits ) & (str$!bits:~|0) ) & 0 5 50 9000 423785674235000123456789:?numbers & whl ' ( !numbers:%?dec ?numbers & put$(str$(!dec ":\n" dec2bin$!dec \n\n)) ) ;
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.
#Phix
Phix
-- demo\rosetta\Bresenham_line.exw (runnable version)   global function bresLine(sequence image, integer x0, y0, x1, y1, colour) -- The line algorithm integer dimx = length(image), dimy = length(image[1]), deltaX = abs(x1-x0), deltaY = abs(y1-y0), stepX = iff(x0<x1,1,-1), stepY = iff(y0<y1,1,-1), lineError = iff(deltaX>deltaY,deltaX,-deltaY), prevle lineError = round(lineError/2, 1) while true do if x0>=1 and x0<=dimx and y0>=1 and y0<=dimy then image[x0][y0] = colour end if if x0=x1 and y0=y1 then exit end if prevle = lineError if prevle>-deltaX then lineError -= deltaY x0 += stepX end if if prevle<deltaY then lineError += deltaX y0 += stepY end if end while return image end function   --include ppm.e -- red, green, blue, white, new_image(), write_ppm(), bresLine() (as distributed, instead of the above)   sequence screenData = new_image(400,300,black) screenData = bresLine(screenData,100,1,50,300,red) screenData = bresLine(screenData,1,180,400,240,green) screenData = bresLine(screenData,200,1,400,150,white) screenData = bresLine(screenData,195,1,205,300,blue) write_ppm("bresenham.ppm",screenData)
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
#Swift
Swift
% if {""} then {puts true} else {puts false} expected boolean value but got ""
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
#Tcl
Tcl
% if {""} then {puts true} else {puts false} expected boolean value but got ""
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
#Trith
Trith
if echo 'Looking for file' # This is the evaluation block test -e foobar.fil # The exit code from this statement determines whether the branch runs then echo 'The file exists' # This is the optional branch echo 'I am going to delete it' rm foobar.fil fi
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)..
#Prolog
Prolog
  compassangle(1, 'North',n, 0.00). compassangle(2, 'North by east', nbe, 11.25). compassangle(3, 'North-northeast', nne,22.50). compassangle(4, 'Northeast by north', nebn,33.75). compassangle(5, 'Northeast', ne,45.00). compassangle(6, 'Norteast by east', nebe,56.25). compassangle(7, 'East-northeast', ene,67.50). compassangle(8, 'East by North', ebn,78.75). compassangle(9, 'East', e,90.00). compassangle(10, 'East by south', ebs, 101.25). compassangle(11, 'East-southeast', ese,112.50). compassangle(12, 'Southeast by east', sebe, 123.75). compassangle(13, 'Southeast', se, 135.00). compassangle(14, 'Southeast by south', sebs, 146.25). compassangle(15, 'South-southeast',sse, 157.50). compassangle(16, 'South by east', sbe, 168.75). compassangle(17, 'South', s, 180.00). compassangle(18, 'South by west', sbw, 191.25). compassangle(19, 'South-southwest', ssw, 202.50). compassangle(20, 'Southwest by south', swbs, 213.75). compassangle(21, 'Southwest', sw, 225.00). compassangle(22, 'Southwest by west', swbw, 236.25). compassangle(23, 'West-southwest', wsw, 247.50). compassangle(24, 'West by south', wbs, 258.75). compassangle(25, 'West', w, 270.00). compassangle(26, 'West by north', wbn, 281.25). compassangle(27, 'West-northwest', wnw, 292.50). compassangle(28, 'Northwest by west', nwbw, 303.75). compassangle(29, 'Northwest', nw, 315.00). compassangle(30, 'Northwest by north', nwbn, 326.25). compassangle(31, 'North-northwest', nnw, 337.50). compassangle(32, 'North by west', nbw, 348.75). compassangle(1, 'North', n, 360.00). compassangle(Index , Name, Heading, Angle) :- nonvar(Angle), resolveindex(Angle, Index), compassangle(Index,Name, Heading, _).   resolveindex(Angle, Index) :- N is Angle / 11.25 + 0.5, I is floor(N),Index is (I mod 32) + 1.  
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.
#JavaScript
JavaScript
function bitwise(a, b){ alert("a AND b: " + (a & b)); alert("a OR b: "+ (a | b)); alert("a XOR b: "+ (a ^ b)); alert("NOT a: " + ~a); alert("a << b: " + (a << b)); // left shift alert("a >> b: " + (a >> b)); // arithmetic right shift alert("a >>> b: " + (a >>> b)); // logical right shift }
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.
#OxygenBasic
OxygenBasic
  'GENERIC BITMAP   type pixel byte r,g,b   '=========== class BitMap '===========   % sp sizeof(pixel) sys wx,wy,px,py string buf sys pb method Constructor(sys x=640,y=480) { wx=x : wy=y : buf=nuls x*y*sp : pb=strptr buf} method Destructor() {buf="" : wx=0 : wy=0 : pb=0} method GetPixel(sys x,y,pixel*p) {copy @p,pb+(y*wx+x)*sp,sp} method SetPixel(sys x,y,pixel*p) {copy pb+(y*wx+x)*sp,@p,sp} ' method Fill(pixel*p) sys i, e=wx*wy*sp+pb-1 for i=pb to e step sp {copy i,@p,sp} end method   end class   pixel p,q   new BitMap m(400,400) 'width, height in pixels   p<=100,120,140 'red,green,blue   m.fill p   m.getPixel 200,100,q print "" q.r "," q.g "," q.b 'result 100,120,140 q<=10,20,40 m.setPixel 200,100,q m.getPixel 200,100,p print "" p.r "," p.g "," p.b 'result 10,20,40     del m  
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.
#Oz
Oz
functor export New Get Set Transform define fun {New Width Height Init} C = {Array.new 1 Height unit} in for Row in 1..Height do C.Row := {Array.new 1 Width Init} end   array2d(width:Width height:Height contents:C) end   fun {Get array2d(contents:C ...) X Y} C.Y.X end   proc {Set array2d(contents:C ...) X Y Val} C.Y.X := Val end   proc {Transform array2d(contents:C width:W height:H ...) Fun} for Y in 1..H do for X in 1..W do C.Y.X := {Fun C.Y.X} end end end   %% omitted: Clone, Map, Fold, ForAll end
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
#Scheme
Scheme
; Given the remainder of the previous row and the final cons of the current row, ; extend (in situ) the current row to be a complete row of the Bell triangle. ; Return the final value in the extended row (for use in computing the following row).   (define bell-triangle-row-extend (lambda (prevrest thisend) (cond ((null? prevrest) (car thisend)) (else (set-cdr! thisend (list (+ (car prevrest) (car thisend)))) (bell-triangle-row-extend (cdr prevrest) (cdr thisend))))))   ; Return the Bell triangle of rows 0 through N (as a list of lists).   (define bell-triangle (lambda (n) (let* ((tri (list (list 1))) (triend tri) (rowendval (caar tri))) (do ((index 0 (1+ index))) ((>= index n) tri) (let ((nextrow (list rowendval))) (set! rowendval (bell-triangle-row-extend (car triend) nextrow)) (set-cdr! triend (list nextrow)) (set! triend (cdr triend)))))))   ; Print out the Bell numbers 0 through 19 and 49 thgough 51. ; (The Bell numbers are the first number on each row of the Bell triangle.)   (printf "~%The Bell numbers:~%") (let loop ((triangle (bell-triangle 51)) (count 0)) (when (pair? triangle) (when (or (<= count 19) (>= count 49)) (printf " ~2d: ~:d~%" count (caar triangle))) (loop (cdr triangle) (1+ count))))   ; Print out the Bell triangle of 10 rows.   (printf "~%First 10 rows of the Bell triangle:~%") (let rowloop ((triangle (bell-triangle 9))) (when (pair? triangle) (let eleloop ((rowlist (car triangle))) (when (pair? rowlist) (printf " ~7:d" (car rowlist)) (eleloop (cdr rowlist)))) (newline) (rowloop (cdr triangle))))
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 .
#PARI.2FGP
PARI/GP
distribution(v)={ my(t=vector(9,n,sum(i=1,#v,v[i]==n))); print("Digit\tActual\tExpected"); for(i=1,9,print(i, "\t", t[i], "\t", round(#v*(log(i+1)-log(i))/log(10)))) }; dist(f)=distribution(vector(1000,n,digits(f(n))[1])); lucas(n)=fibonacci(n-1)+fibonacci(n+1); dist(fibonacci) dist(lucas)
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   +½.
#Lua
Lua
#!/usr/bin/env luajit local gmp = require 'gmp' ('libgmp') local ffi = require'ffi' local mpz, mpq = gmp.types.z, gmp.types.q local function mpq_for(buf, op, n) for i=0,n-1 do op(buf[i]) end end local function bernoulli(rop, n) local a=ffi.new("mpq_t[?]", n+1) mpq_for(a, gmp.q_init, n+1)   for m=0,n do gmp.q_set_ui(a[m],1, m+1) for j=m,1,-1 do gmp.q_sub(a[j-1], a[j], a[j-1]) gmp.q_set_ui(rop, j, 1) gmp.q_mul(a[j-1], a[j-1], rop) end end gmp.q_set(rop,a[0]) mpq_for(a, gmp.q_clear, n+1) end do --MAIN local rop=mpq() local n,d=mpz(),mpz() gmp.q_init(rop) gmp.z_inits(n, d) local to=arg[1] and tonumber(arg[1]) or 60 local from=arg[2] and tonumber(arg[2]) or 0 if from~=0 then to,from=from,to end     for i=from,to do bernoulli(rop, i) if gmp.q_cmp_ui(rop, 0, 1)~=0 then gmp.q_get_num(n, rop) gmp.q_get_den(d, rop) gmp.printf("B(%-2g) = %44Zd / %Zd\n", i, n, d) end end gmp.z_clears(n,d) gmp.q_clear(rop) 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.
#Crystal
Crystal
class Array def binary_search(val, low = 0, high = (size - 1)) return nil if high < low #mid = (low + high) >> 1 mid = low + ((high - low) >> 1) case val <=> self[mid] when -1 binary_search(val, low, mid - 1) when 1 binary_search(val, mid + 1, high) else mid end end end   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]   [0, 42, 45, 24324, 99999].each do |val| i = ary.binary_search(val) if i puts "found #{val} at index #{i}: #{ary[i]}" else puts "#{val} not found in array" end end