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/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
#OCaml
OCaml
let best_shuffle s = let len = String.length s in let r = String.copy s in for i = 0 to pred len do for j = 0 to pred len do if i <> j && s.[i] <> r.[j] && s.[j] <> r.[i] then begin let tmp = r.[i] in r.[i] <- r.[j]; r.[j] <- tmp; end done; done; (r)   let count_same s1 s2 = let len1 = String.length s1 and len2 = String.length s2 in let n = ref 0 in for i = 0 to pred (min len1 len2) do if s1.[i] = s2.[i] then incr n done; !n   let () = let test s = let s2 = best_shuffle s in Printf.printf " '%s', '%s' -> %d\n" s s2 (count_same s s2); in test "tree"; test "abracadabra"; test "seesaw"; test "elk"; test "grrrrrr"; test "up"; test "a"; ;;
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#Raku
Raku
# Raku is perfectly fine with NUL *characters* in strings: my Str $s = 'nema' ~ 0.chr ~ 'problema!'; say $s;   # However, Raku makes a clear distinction between strings # (i.e. sequences of characters), like your name, or … my Str $str = "My God, it's full of chars!"; # … and sequences of bytes (called Bufs), for example a PNG image, or … my Buf $buf = Buf.new(255, 0, 1, 2, 3); say $buf;   # Strs can be encoded into Blobs … my Blob $this = 'round-trip'.encode('ascii'); # … and Blobs can be decoded into Strs … my Str $that = $this.decode('ascii');   # So it's all there. Nevertheless, let's solve this task explicitly # in order to see some nice language features:   # We define a class … class ByteStr { # … that keeps an array of bytes, and we delegate some # straight-forward stuff directly to this attribute: # (Note: "has byte @.bytes" would be nicer, but that is # not yet implemented in Rakudo.) has Int @.bytes handles(< Bool elems gist push >);   # A handful of methods … method clone() { self.new(:@.bytes); }   method substr(Int $pos, Int $length) { self.new(:bytes(@.bytes[$pos .. $pos + $length - 1])); }   method replace(*@substitutions) { my %h = @substitutions; @.bytes.=map: { %h{$_} // $_ } } }   # A couple of operators for our new type: multi infix:<cmp>(ByteStr $x, ByteStr $y) { $x.bytes.join cmp $y.bytes.join } multi infix:<~> (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes(|$x.bytes, |$y.bytes)) }   # create some byte strings (destruction not needed due to garbage collection) my ByteStr $b0 = ByteStr.new; my ByteStr $b1 = ByteStr.new(:bytes( |'foo'.ords, 0, 10, |'bar'.ords ));   # assignment ($b1 and $b2 contain the same ByteStr object afterwards): my ByteStr $b2 = $b1;   # comparing: say 'b0 cmp b1 = ', $b0 cmp $b1; say 'b1 cmp b2 = ', $b1 cmp $b2;   # cloning: my $clone = $b1.clone; $b1.replace('o'.ord => 0); say 'b1 = ', $b1; say 'b2 = ', $b2; say 'clone = ', $clone;   # to check for (non-)emptiness we evaluate the ByteStr in boolean context: say 'b0 is ', $b0 ?? 'not empty' !! 'empty'; say 'b1 is ', $b1 ?? 'not empty' !! 'empty';   # appending a byte: $b1.push: 123; say 'appended = ', $b1;   # extracting a substring: my $sub = $b1.substr(2, 4); say 'substr = ', $sub;   # replacing a byte: $b2.replace(102 => 103); say 'replaced = ', $b2;   # joining: my ByteStr $b3 = $b1 ~ $sub; say 'joined = ', $b3;
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.
#Brainf.2A.2A.2A
Brainf***
+[ Start with n=1 to kick off the loop [>>++<< Set up {n 0 2} for divmod magic [->+>- Then [>+>>]> do [+[-<+>]>+>>] the <<<<<<] magic >>>+ Increment n % 2 so that 0s don't break things >] Move into n / 2 and divmod that unless it's 0 -< Set up sentinel ‑1 then move into the first binary digit [++++++++ ++++++++ ++++++++ Add 47 to get it to ASCII ++++++++ ++++++++ +++++++. and print it [<]<] Get to a 0; the cell to the left is the next binary digit >>[<+>-] Tape is {0 n}; make it {n 0} >[>+] Get to the ‑1 <[[-]<] Zero the tape for the next iteration ++++++++++. Print a newline [-]<+] Zero it then increment n and go again
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.
#PicoLisp
PicoLisp
(de brez (Img X Y DX DY) (let SX (cond ((=0 DX) 0) ((gt0 DX) 1) (T (setq DX (- DX)) -1) ) (let SY (cond ((=0 DY) 0) ((gt0 DY) 1) (T (setq DY (- DY)) -1) ) (if (>= DX DY) (let E (- (* 2 DY) DX) (do DX (set (nth Img Y X) 1) (when (ge0 E) (inc 'Y SY) (dec 'E (* 2 DX)) ) (inc 'X SX) (inc 'E (* 2 DY)) ) ) (let E (- (* 2 DX) DY) (do DY (set (nth Img Y X) 1) (when (ge0 E) (inc 'X SX) (dec 'E (* 2 DY)) ) (inc 'Y SY) (inc 'E (* 2 DX)) ) ) ) ) ) )   (let Img (make (do 90 (link (need 120 0)))) # Create image 120 x 90 (brez Img 10 10 100 30) # Draw five lines (brez Img 10 10 100 50) (brez Img 10 10 100 70) (brez Img 10 10 60 70) (brez Img 10 10 20 70) (out "img.pbm" # Write to bitmap file (prinl "P1") (prinl 120 " " 90) (mapc prinl Img) ) )
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
#UNIX_Shell
UNIX Shell
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/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
#Ursa
Ursa
decl boolean bool
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
#VBA
VBA
Dim a As Integer Dim b As Boolean Debug.Print b a = b Debug.Print a b = True Debug.Print b a = b Debug.Print a
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)..
#PureBasic
PureBasic
DataSection Data.s "N", "north", "E", "east", "W", "west", "S", "south", "b", " by " ;abbreviations, expansions Data.s "N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE" ;dirs Data.s "S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW" EndDataSection   ;initialize data NewMap dirSubst.s() Define i, abbr.s, expansion.s For i = 1 To 5 Read.s abbr Read.s expansion dirSubst(abbr) = expansion Next   Dim dirs.s(32) Define j, s.s For j = 0 To 1 Read.s s.s For i = 0 To 15 abbr.s = StringField(s, i + 1, " ") dirs(j * 16 + i) = abbr Next Next   ;expand abbreviated compass point and capitalize Procedure.s abbr2compassPoint(abbr.s) Shared dirSubst() Protected i, compassPoint.s, key.s   For i = 1 To Len(abbr) key.s = Mid(abbr, i, 1) If FindMapElement(dirSubst(), key) compassPoint + dirSubst(key) Else compassPoint + key EndIf Next ProcedureReturn UCase(Left(compassPoint, 1)) + Mid(compassPoint, 2) EndProcedure   Procedure.s angle2compass(angle.f) Shared dirs() Static segment.f = 360.0 / 32 ;width of each compass segment Protected dir   ;work out which segment contains the compass angle dir = Int((Mod(angle, 360) / segment) + 0.5)   ;convert to a named direction ProcedureReturn abbr2compassPoint(dirs(dir)) EndProcedure   ;box the compass If OpenConsole()   Define i, heading.f, index For i = 0 To 32 heading = i * 11.25 If i % 3 = 1 heading + 5.62 EndIf If i % 3 = 2 heading - 5.62 EndIf index = i % 32 + 1   PrintN(RSet(Str(index), 2) + " " + LSet(angle2compass(heading), 18) + RSet(StrF(heading, 2), 7)) Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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.
#Julia
Julia
# Version 5.2 @show 1 & 2 # AND @show 1 | 2 # OR @show 1 ^ 2 # XOR -- for Julia 6.0 the operator is `⊻` @show ~1 # NOT @show 1 >>> 2 # SHIFT RIGHT (LOGICAL) @show 1 >> 2 # SHIFT RIGHT (ARITMETIC) @show 1 << 2 # SHIFT LEFT (ARITMETIC/LOGICAL)   A = BitArray([true, true, false, false, true]) @show A ror(A,1) ror(A,2) ror(A,5) # ROTATION RIGHT @show rol(A,1) rol(A,2) rol(A,5) # ROTATION LEFT  
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.
#Pascal
Pascal
Interface uses crt, { GetDir } graph; { function GetPixel }   type { integer numbers } { from unit bitmaps XPERT software production Tamer Fakhoury } _bit = $00000000..$00000001; {number 1 bit without sign = (0..1) } _byte = $00000000..$000000FF; {number 1 byte without sign = (0..255)} _word = $00000000..$0000FFFF; {number 2 bytes without sign = (0..65 535)} _dWord = $00000000..$7FFFFFFF; {number 4 bytes without sign = (0..4 294 967 296)} _longInt = $80000000..$7FFFFFFF; {number 4 bytes with sign = (-2 147 483 648..2 147 483 648}   TbmpFileHeader = record ID: _word; { Must be 'BM' =19778=$424D for windows } FileSize: _dWord; { Size of this file in bytes } Reserved: _dWord; { ??? } bmpDataOffset: _dword; { = 54 = $36 from begining of file to begining of bmp data } end;   TbmpInfoHeader = record InfoHeaderSize: _dword; { Size of Info header = 28h = 40 (decimal) for windows } Width, Height: _longInt; { Width and Height of image in pixels } Planes, { number of planes of bitmap } BitsPerPixel: _word; { Bits can be 1, 4, 8, 24 or 32 } Compression, bmpDataSize: _dword; { in bytes rounded to the next 4 byte boundary } XPixPerMeter, { horizontal resolution in pixels } YPixPerMeter: _longInt; { vertical } NumbColorsUsed, NumbImportantColors: _dword; {= NumbColorUsed} end; { TbmpHeader = Record ... }   T32Color = record { 4 byte = 32 bit } Blue: byte; Green: byte; Red: byte; Alfa: byte end;   var directory, bmpFileName: string; bmpFile: file; { untyped file } bmpFileHeader: TbmpFileHeader; bmpInfoHeader: TbmpInfoHeader; color32: T32Color; RowSizeInBytes: integer; BytesPerPixel: integer;   const defaultBmpFileName = 'test'; DefaultDirectory = 'c:\bp\'; DefaultExtension = '.bmp'; bmpFileHeaderSize = 14; { compression specyfication } bi_RGB = 0; { compression } bi_RLE8 = 1; bi_RLE4 = 2; bi_BITFIELDS = 3;   bmp_OK = 0; bmp_NotBMP = 1; bmp_OpenError = 2; bmp_ReadError = 3;   Procedure CreateBmpFile32(directory: string; FileName: string; iWidth, iHeight: _LongInt);   {************************************************} Implementation {-----------------------------} {************************************************}   Procedure CreateBmpFile32(directory: string; FileName: string; iWidth, iHeight: _LongInt); var x, y: integer; begin if directory = '' then GetDir(0, directory); if FileName = '' then FileName: = DefaultBmpFileName; { create a new file on a disk in a given directory with given name } Assign(bmpFile, directory + FileName + DefaultExtension); ReWrite(bmpFile, 1);   { fill the headers } with bmpInfoHeader, bmpFileHeader do begin ID := 19778; InfoheaderSize := 40; width := iWidth; height := iHeight; BitsPerPixel := 32; BytesPerPixel := BitsPerPixel div 8; reserved := 0; bmpDataOffset := InfoHeaderSize + bmpFileHeaderSize; planes := 1; compression := bi_RGB; XPixPerMeter := 0; YPixPerMeter := 0; NumbColorsUsed := 0; NumbImportantColors := 0;   RowSizeInBytes := (Width * BytesPerPixel); { only for >=8 bits per pixel } bmpDataSize := height * RowSizeinBytes; FileSize := InfoHeaderSize + bmpFileHeaderSize + bmpDataSize;   { copy headers to disk file } BlockWrite(bmpFile, bmpFileHeader, bmpFileHeaderSize); BlockWrite(bmpFile, bmpInfoHeader, infoHeaderSize);   { fill the pixel data area } for y := (height - 1) downto 0 do begin for x := 0 to (width - 1) do begin { Pixel(x,y) } color32.Blue := 255; color32.Green := 0; color32.Red := 0; color32.Alfa := 0; BlockWrite(bmpFile, color32, 4); end; { for x ... } end; { for y ... } Close(bmpFile); end; { with bmpInfoHeader, bmpFileHeader } end; { procedure }  
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
#Sidef
Sidef
say 15.of { .bell }
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
#Swift
Swift
public struct BellTriangle<T: BinaryInteger> { @usableFromInline var arr: [T]   @inlinable public internal(set) subscript(row row: Int, col col: Int) -> T { get { arr[row * (row - 1) / 2 + col] } set { arr[row * (row - 1) / 2 + col] = newValue } }   @inlinable public init(n: Int) { arr = Array(repeating: 0, count: n * (n + 1) / 2)   self[row: 1, col: 0] = 1   for i in 2...n { self[row: i, col: 0] = self[row: i - 1, col: i - 2]   for j in 1..<i { self[row: i, col: j] = self[row: i, col: j - 1] + self[row: i - 1, col: j - 1] } } } }   let tri = BellTriangle<Int>(n: 15)   print("First 15 Bell numbers:")   for i in 1...15 { print("\(i): \(tri[row: i, col: 0])") }   for i in 1...10 { print(tri[row: i, col: 0], terminator: "")   for j in 1..<i { print(", \(tri[row: i, col: j])", terminator: "") }   print() }
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 .
#Pascal
Pascal
program fibFirstdigit; {$IFDEF FPC}{$MODE Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; type tDigitCount = array[0..9] of LongInt; var s: Ansistring; dgtCnt, expectedCnt : tDigitCount;   procedure GetFirstDigitFibonacci(var dgtCnt:tDigitCount;n:LongInt=1000); //summing up only the first 9 digits //n = 1000 -> difference to first 9 digits complete fib < 100 == 2 digits var a,b,c : LongWord;//about 9.6 decimals Begin for a in dgtCnt do dgtCnt[a] := 0; a := 0;b := 1; while n > 0 do Begin c := a+b; //overflow? round and divide by base 10 IF c < a then Begin a := (a+5) div 10;b := (b+5) div 10;c := a+b;end; a := b;b := c; s := IntToStr(a);inc(dgtCnt[Ord(s[1])-Ord('0')]); dec(n); end; end;   procedure InitExpected(var dgtCnt:tDigitCount;n:LongInt=1000); var i: integer; begin for i := 1 to 9 do dgtCnt[i] := trunc(n*ln(1 + 1 / i)/ln(10)); end;   var reldiff: double; i,cnt: integer; begin cnt := 1000; InitExpected(expectedCnt,cnt); GetFirstDigitFibonacci(dgtCnt,cnt); writeln('Digit count expected rel diff'); For i := 1 to 9 do Begin reldiff := 100*(expectedCnt[i]-dgtCnt[i])/expectedCnt[i]; writeln(i:5,dgtCnt[i]:7,expectedCnt[i]:10,reldiff:10:5,' %'); end; 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   +½.
#Maple
Maple
print(select(n->n[2]<>0,[seq([n,bernoulli(n,1)],n=0..60)]));
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   +½.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
bernoulli[n_] := Module[{a = ConstantArray[0, n + 2]}, Do[ a[[m]] = 1/m; If[m == 1 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; Do[ a[[j - 1]] = (j - 1)*(a[[j - 1]] - a[[j]]); If[j == 2 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; , {j, m, 2, -1}]; , {m, 1, n + 1}]; ] bernoulli[60]
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.
#D
D
import std.stdio, std.array, std.range, std.traits;   /// Recursive. bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) { if (data.empty) return false; immutable i = data.length / 2; immutable mid = data[i]; if (mid > x) return data[0 .. i].binarySearch(x); if (mid < x) return data[i + 1 .. $].binarySearch(x); return true; }   /// Iterative. bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) { while (!data.empty) { immutable i = data.length / 2; immutable mid = data[i]; if (mid > x) data = data[0 .. i]; else if (mid < x) data = data[i + 1 .. $]; else return true; } return false; }   void main() { /*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted; foreach (const x; [1, 8, 10, 9, 5, 2]) writefln("%2d %5s %5s %5s", x, items.binarySearch(x), items.binarySearchIt(x), // Standard Binary Search: !items.equalRange(x).empty); }
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
#Pascal
Pascal
program BestShuffleDemo(output);   function BestShuffle(s: string): string;   var tmp: char; i, j: integer; t: string; begin t := s; for i := 1 to length(t) do for j := 1 to length(t) do if (i <> j) and (s[i] <> t[j]) and (s[j] <> t[i]) then begin tmp := t[i]; t[i] := t[j]; t[j] := tmp; end; BestShuffle := t; end;   const original: array[1..6] of string = ('abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a');   var shuffle: string; i, j, score: integer;   begin for i := low(original) to high(original) do begin shuffle := BestShuffle(original[i]); score := 0; for j := 1 to length(shuffle) do if original[i][j] = shuffle[j] then inc(score); writeln(original[i], ', ', shuffle, ', (', score, ')'); end; 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.
#Red
Red
Red [] s: copy "abc" ;; string creation   s: none ;; destruction t: "Abc" if t == "abc" [print "equal case"] ;; comparison , case sensitive if t = "abc" [print "equal (case insensitive)"] ;; comparison , case insensitive s: copy "" ;; copying string if empty? s [print "string is empty "] ;; check if string is empty append s #"a" ;; append byte substr: copy/part at "1234" 3 2 ;; ~ substr ("1234" ,3,2) , red has 1 based indices ! ?? substr s: replace/all "abcabcabc" "bc" "x" ;; replace all "bc" by "x" ?? s s: append "hello " "world" ;; join 2 strings ?? s s: rejoin ["hello " "world" " !"] ;; join multiple strings ?? s  
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.
#Burlesque
Burlesque
  blsq ) {5 50 9000}{2B!}m[uN 101 110010 10001100101000  
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.
#PL.2FI
PL/I
  /* Draw a line from (x0, y0) to (x1, y1). 13 May 2010 */ /* Based on Rosetta code proforma. */   /* Declarations for image and selected color, for 4-bit colors. */ declare image(40,40) bit (4), color bit (4) static initial ('1000'b);   draw_line: procedure (xi, yi, xf, yf ); declare (xi, yi, xf, yf) fixed binary (31) nonassignable; declare (x0, y0, x1, y1) fixed binary (31); declare (deltax, deltay, x, y, ystep) fixed binary; declare (error initial (0), delta_error) float; declare steep bit (1);   x0 = xi; y = YI; y0 = yi; x1 = xf; y1 = yf; steep = abs(y1 - y0) > abs (x1 - x0); if steep then do; call swap (x0, y0); call swap (x1, y1); end; if x0 > x1 then do; call swap (x0, x1); call swap (y0, y1); end; deltax = x1 - x0; deltay = abs(y1 - y0); delta_error = deltay/deltax; if y0 < y1 then ystep = 1; else ystep = -1; do x = x0 to x1; if steep then image(y, x) = color; else image(x, y) = color; if steep then put skip list (y, x); else put skip list (x, y); error = error + delta_error; if error >= 0.5 then do; y = y + ystep; error = error - 1; end; end;   swap: procedure (a, b); declare (a, b) fixed binary (31); declare t fixed binary (31); t = a; a = b; b = t; end swap;   end draw_line;  
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
#VBScript
VBScript
  a = True b = False Randomize Timer x = Int(Rnd * 2) <> 0 y = Int(Rnd * 2) = 0 MsgBox a & " " & b & " " & x & " " & y
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
#Vim_Script
Vim Script
if "foo" echo "true" else echo "false" endif
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
#Vlang
Vlang
// Boolean Value, in V // Tectonics: v run boolean-value.v module main   // V bool type, with values true or false are the V booleans. // true and false are V keywords, and display as true/false // Numeric values are not booleans in V, 0 is not boolean false pub fn main() { t := true f := false   if t { println(t) }   // this code would fail to compile // if 1 { println(t) }   if 0 == 1 { println("bad result") } else { println(f) } }
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)..
#Python
Python
majors = 'north east south west'.split() majors *= 2 # no need for modulo later quarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',') quarter2 = [p.replace('NE','EN') for p in quarter1]   def degrees2compasspoint(d): d = (d % 360) + 360/64 majorindex, minor = divmod(d, 90.) majorindex = int(majorindex) minorindex = int( (minor*4) // 45 ) p1, p2 = majors[majorindex: majorindex+2] if p1 in {'north', 'south'}: q = quarter1 else: q = quarter2 return q[minorindex].replace('N', p1).replace('E', p2).capitalize()   if __name__ == '__main__': for i in range(33): d = i * 11.25 m = i % 3 if m == 1: d += 5.62 elif m == 2: d -= 5.62 n = i % 32 + 1 print( '%2i %-18s %7.2f°' % (n, degrees2compasspoint(d), d) )
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.
#Kotlin
Kotlin
/* for symmetry with Kotlin's other binary bitwise operators we wrap Java's 'rotate' methods as infix functions */ infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance)   fun main(args: Array<String>) { // inferred type of x and y is Int i.e. 32 bit signed integers val x = 10 val y = 2 println("x = $x") println("y = $y") println("NOT x = ${x.inv()}") println("x AND y = ${x and y}") println("x OR y = ${x or y}") println("x XOR y = ${x xor y}") println("x SHL y = ${x shl y}") println("x ASR y = ${x shr y}") // arithmetic shift right (sign bit filled) println("x LSR y = ${x ushr y}") // logical shift right (zero filled) println("x ROL y = ${x rol y}") println("x ROR y = ${x ror y}") }
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.
#Perl
Perl
#! /usr/bin/perl   use strict;   use Image::Imlib2;   # create the "canvas" my $img = Image::Imlib2->new(200,200);   # fill with a plain RGB(A) color $img->set_color(255, 0, 0, 255); $img->fill_rectangle(0,0, 200, 200);   # set a pixel to green (at 40,40) $img->set_color(0, 255, 0, 255); $img->draw_point(40,40);   # "get" pixel rgb(a) my ($red, $green, $blue, $alpha) = $img->query_pixel(40,40); undef $img;   # another way of creating a canvas with a bg colour (or from # an existing "raw" data) my $col = pack("CCCC", 255, 255, 0, 0); # a, r, g, b my $img = Image::Imlib2->new_using_data(200, 200, $col x (200 * 200));   exit 0;
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
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Sub Init(Of T)(array As T(), value As T) If IsNothing(array) Then Return For i = 0 To array.Length - 1 array(i) = value Next End Sub   Function BellTriangle(n As Integer) As BigInteger()() Dim tri(n - 1)() As BigInteger For i = 0 To n - 1 Dim temp(i - 1) As BigInteger tri(i) = temp tri(i).Init(0) Next tri(1)(0) = 1 For i = 2 To n - 1 tri(i)(0) = tri(i - 1)(i - 2) For j = 1 To i - 1 tri(i)(j) = tri(i)(j - 1) + tri(i - 1)(j - 1) Next Next Return tri End Function   Sub Main() Dim bt = BellTriangle(51) Console.WriteLine("First fifteen Bell numbers:") For i = 1 To 15 Console.WriteLine("{0,2}: {1}", i, bt(i)(0)) Next Console.WriteLine("50: {0}", bt(50)(0)) Console.WriteLine() Console.WriteLine("The first ten rows of Bell's triangle:") For i = 1 To 10 Dim it = bt(i).GetEnumerator() Console.Write("[") If it.MoveNext() Then Console.Write(it.Current) End If While it.MoveNext() Console.Write(", ") Console.Write(it.Current) End While Console.WriteLine("]") Next End Sub   End Module
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 .
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use POSIX qw( log10 ) ;   my @fibonacci = ( 0 , 1 ) ; while ( @fibonacci != 1000 ) { push @fibonacci , $fibonacci[ -1 ] + $fibonacci[ -2 ] ; } my @actuals ; my @expected ; for my $i( 1..9 ) { my $sum = 0 ; map { $sum++ if $_ =~ /\A$i/ } @fibonacci ; push @actuals , $sum / 1000 ; push @expected , log10( 1 + 1/$i ) ; } print " Observed Expected\n" ; for my $i( 1..9 ) { print "$i : " ; my $result = sprintf ( "%.2f" , 100 * $actuals[ $i - 1 ] ) ; printf "%11s %%" , $result ; $result = sprintf ( "%.2f" , 100 * $expected[ $i - 1 ] ) ; printf "%15s %%\n" , $result ; }
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   +½.
#Nim
Nim
import bignum import strformat   const Lim = 60   #---------------------------------------------------------------------------------------------------   proc bernoulli(n: Natural): Rat = ## Compute a Bernoulli number using Akiyama–Tanigawa algorithm.   var a = newSeq[Rat](n + 1) for m in 0..n: a[m] = newRat(1, m + 1) for j in countdown(m, 1): a[j-1] = j * (a[j] - a[j-1]) result = a[0]     #———————————————————————————————————————————————————————————————————————————————————————————————————   type Info = tuple n: int # Number index in Bernoulli sequence. val: Rat # Bernoulli number.   var values: seq[Info] # List of values as Info tuples. var maxLen = -1 # Maximum length.   # First step: compute the values and prepare for display. for n in 0..Lim: # Compute value. if n != 1 and (n and 1) == 1: continue # Ignore odd "n" except 1. let b = bernoulli(n) # Check numerator length. let len = ($b.num).len if len > maxLen: maxLen = len # Store information for next step. values.add((n, b))   # Second step: display the values with '/' aligned. for (n, b) in values: let s = fmt"{($b.num).alignString(maxLen, '>')} / {b.denom}" echo fmt"{n:2}: {s}"
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.
#Delphi
Delphi
/** Returns null if the value is not found. */ def binarySearch(collection, value) { var low := 0 var high := collection.size() - 1 while (low <= high) { def mid := (low + high) // 2 def comparison := value.op__cmp(collection[mid]) if (comparison.belowZero()) { high := mid - 1 } \ else if (comparison.aboveZero()) { low := mid + 1 } \ else if (comparison.isZero()) { return mid } \ else { throw("You expect me to binary search with a partial order?") } } return null }
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
#Perl
Perl
use strict; use warnings; use List::Util qw(shuffle); use Algorithm::Permute;   best_shuffle($_) for qw(abracadabra seesaw elk grrrrrr up a);   sub best_shuffle { my ($original_word) = @_; my $best_word = $original_word; my $best_score = length $best_word;   my @shuffled = shuffle split //, $original_word; my $iterator = Algorithm::Permute->new(\@shuffled);   while( my @array = $iterator->next ) { my $word = join '', @array; # For each letter which is the same in the two words, # there will be a \x00 in the "^" of the two words. # The tr operator is then used to count the "\x00"s. my $score = ($original_word ^ $word) =~ tr/\x00//; next if $score >= $best_score; ($best_word, $best_score) = ($word, $score); last if $score == 0; }   print "$original_word, $best_word, $best_score\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.
#REXX
REXX
/*REXX program demonstrates methods (code examples) to use and express binary strings.*/ dingsta= '11110101'b /*four versions, bit string assignment.*/ dingsta= "11110101"b /*this is the same assignment as above.*/ dingsta= '11110101'B /* " " " " " " " */ dingsta= '1111 0101'B /* " " " " " " */   dingsta2= dingsta /*clone one string to another (a copy).*/ other= '1001 0101 1111 0111'b /*another binary (or bit) string. */ if dingsta= other then say 'they are equal' /*compare the two (binary) strings. */ if other== '' then say "OTHER is empty." /*see if the OTHER string is empty.*/ otherA= other || '$' /*append a dollar sign ($) to OTHER. */ otherB= other'$' /*same as above, but with less fuss. */ guts= substr(c2b(other), 10, 3) /*obtain the 10th through 12th bits.*/ new= changeStr('A' , other, "Z") /*change the upper letter A ──► Z. */ tt= changeStr('~~', other, ";") /*change two tildes ──► one semicolon.*/ joined= dingsta || dingsta2 /*join two strings together (concat). */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ c2b: return x2b( c2x( arg(1) ) ) /*return the string as a binary string.*/
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.
#C
C
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings #define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS   #include <stdio.h> #include <stdlib.h>     char* bin2str(unsigned value, char* buffer) { // This algorithm is not the fastest one, but is relativelly simple. // // A faster algorithm would be conversion octets to strings by a lookup table. // There is only 2**8 == 256 octets, therefore we would need only 2048 bytes // for the lookup table. Conversion of a 64-bit integers would need 8 lookups // instead 64 and/or/shifts of bits etc. Even more... lookups may be implemented // with XLAT or similar CPU instruction... and AVX/SSE gives chance for SIMD.   const unsigned N_DIGITS = sizeof(unsigned) * 8; unsigned mask = 1 << (N_DIGITS - 1); char* ptr = buffer;   for (int i = 0; i < N_DIGITS; i++) { *ptr++ = '0' + !!(value & mask); mask >>= 1; } *ptr = '\0';   // Remove leading zeros. // for (ptr = buffer; *ptr == '0'; ptr++) ;   return ptr; }     char* bin2strNaive(unsigned value, char* buffer) { // This variation of the solution doesn't use bits shifting etc.   unsigned n, m, p;   n = 0; p = 1; // p = 2 ** n while (p <= value / 2) { n = n + 1; p = p * 2; }   m = 0; while (n > 0) { buffer[m] = '0' + value / p; value = value % p; m = m + 1; n = n - 1; p = p / 2; }   buffer[m + 1] = '\0'; return buffer; }     int main(int argc, char* argv[]) { const unsigned NUMBERS[] = { 5, 50, 9000 };   const int RADIX = 2; char buffer[(sizeof(unsigned)*8 + 1)];   // Function itoa is an POSIX function, but it is not in C standard library. // There is no big surprise that Microsoft deprecate itoa because POSIX is // "Portable Operating System Interface for UNIX". Thus it is not a good // idea to use _itoa instead itoa: we lost compatibility with POSIX; // we gain nothing in MS Windows (itoa-without-underscore is not better // than _itoa-with-underscore). The same holds for kbhit() and _kbhit() etc. // for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++) { unsigned value = NUMBERS[i]; itoa(value, buffer, RADIX); printf("itoa:  %u decimal = %s binary\n", value, buffer); }   // Yeep, we can use a homemade bin2str function. Notice that C is very very // efficient (as "hi level assembler") when bit manipulation is needed. // for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++) { unsigned value = NUMBERS[i]; printf("bin2str:  %u decimal = %s binary\n", value, bin2str(value, buffer)); }   // Another implementation - see above. // for (int i = 0; i < sizeof(NUMBERS) / sizeof(unsigned); i++) { unsigned value = NUMBERS[i]; printf("bin2strNaive:  %u decimal = %s binary\n", value, bin2strNaive(value, buffer)); }   return EXIT_SUCCESS; }  
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.
#Prolog
Prolog
  :- use_module(bitmap). :- use_module(bitmapIO). :- use_module(library(clpfd)).   % ends when X1 = X2 and Y1 = Y2 draw_recursive_line(NPict,Pict,Color,X,X,_DX,_DY,Y,Y,_E,_Sx,_Sy):- set_pixel0(NPict,Pict,[X,Y],Color). draw_recursive_line(NPict,Pict,Color,X,X2,DX,DY,Y,Y2,E,Sx,Sy):- set_pixel0(TPict,Pict,[X,Y],Color), E2 #= 2*E, % because we can't accumulate error we set Ey or Ex to 1 or 0 % depending on whether we need to add dY or dX to the error term ( E2 >= DY -> Ey = 1, NX #= X + Sx; Ey = 0, NX = X), ( E2 =< DX -> Ex = 1, NY #= Y + Sy; Ex = 0, NY = Y), NE #= E + DX*Ex + DY*Ey, draw_recursive_line(NPict,TPict,Color,NX,X2,DX,DY,NY,Y2,NE,Sx,Sy).   draw_line(NPict,Pict,Color,X1,Y1,X2,Y2):- DeltaY #= Y2-Y1, DeltaX #= X2-X1, ( DeltaY < 0 -> Sy = -1; Sy = 1), ( DeltaX < 0 -> Sx = -1; Sx = 1), DX #= abs(DeltaX), DY #= -1*abs(DeltaY), E #= DY+DX, draw_recursive_line(NPict,Pict,Color,X1,X2,DX,DY,Y1,Y2,E,Sx,Sy).     init:- new_bitmap(B,[100,100],[255,255,255]), draw_line(NB,B,[0,0,0],2,2,10,90), write_ppm_p6('line.ppm',NB).  
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
#WDTE
WDTE
let io => import 'io'; let ex => switch 'this is irrelevant for this example' { false => 'This is, obviously, not returned.'; 'a string' => 'This is also not returned.'; true => 'This is returned.'; }; ex -- io.writeln io.stdout;
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
#Wren
Wren
var embed = true System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])
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)..
#QBasic
QBasic
DECLARE FUNCTION compasspoint$ (h!)   DIM SHARED POINT$(32)   FOR i = 1 TO 32 READ d$: POINT$(i) = d$ NEXT i   FOR i = 0 TO 32 heading = i * 11.25 IF (i MOD 3) = 1 THEN heading = heading + 5.62 ELSE IF (i MOD 3) = 2 THEN heading = heading - 5.62 END IF ind = i MOD 32 + 1 PRINT ind, compasspoint$(heading), heading NEXT i END   DATA "North ", "North by east ", "North-northeast ", "Northeast by north" DATA "Northeast ", "Northeast by east ", "East-northeast ", "East by north " DATA "East ", "East by south ", "East-southeast ", "Southeast by east " DATA "Southeast ", "Southeast by south", "South-southeast ", "South by east " DATA "South ", "South by west ", "South-southwest ", "Southwest by south" DATA "Southwest ", "Southwest by west ", "West-southwest ", "West by south " DATA "West ", "West by north ", "West-northwest ", "Northwest by west " DATA "Northwest ", "Northwest by north", "North-northwest ", "North by west "   FUNCTION compasspoint$ (h) x = h / 11.25 + 1.5 IF (x >= 33!) THEN x = x - 32! compasspoint$ = POINT$(INT(x)) END FUNCTION
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.
#LFE
LFE
(defun bitwise (a b) (lists:map (lambda (x) (io:format "~p~n" `(,x))) `(,(band a b) ,(bor a b) ,(bxor a b) ,(bnot a) ,(bsl a b) ,(bsr a b))) 'ok)   (defun dec->bin (x) (integer_to_list x 2))   (defun describe (func arg1 arg2 result) (io:format "(~s ~s ~s): ~s~n" (list func (dec->bin arg1) (dec->bin arg2) (dec->bin result))))   (defun bitwise ((a b 'binary) (describe "band" a b (band a b)) (describe "bor" a b (bor a b)) (describe "bxor" a b (bxor a b)) (describe "bnot" a b (bnot a)) (describe "bsl" a b (bsl a b)) (describe "bsr" a b (bsr a 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.
#Phix
Phix
with javascript_semantics -- Some colour constants: constant black = #000000, -- blue = #0000FF, -- green = #00FF00, -- red = #FF0000, white = #FFFFFF -- Create new image filled with some colour function new_image(integer width, integer height, integer fill_colour=black) return repeat(repeat(fill_colour,height),width) end function -- Usage example: sequence image = new_image(800,600) -- Set pixel color: image[400][300] = white -- Get pixel color integer colour = image[400][300] -- Now colour is #FFFFFF
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
#Vlang
Vlang
import math.big   fn bell_triangle(n int) [][]big.Integer { mut tri := [][]big.Integer{len: n} for i in 0..n { tri[i] = []big.Integer{len: i} for j in 0..i { tri[i][j] = big.zero_int } } tri[1][0] = big.integer_from_u64(1) for i in 2..n { tri[i][0] = tri[i-1][i-2] for j := 1; j < i; j++ { tri[i][j] = tri[i][j-1] + tri[i-1][j-1] } } return tri }   fn main() { bt := bell_triangle(51) println("First fifteen and fiftieth Bell numbers:") for i := 1; i <= 15; i++ { println("${i:2}: ${bt[i][0]}") } println("50: ${bt[50][0]}") println("\nThe first ten rows of Bell's triangle:") for i := 1; i <= 10; i++ { println(bt[i]) } }
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
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var bellTriangle = Fn.new { |n| var tri = List.filled(n, null) for (i in 0...n) { tri[i] = List.filled(i, null) for (j in 0...i) tri[i][j] = BigInt.zero } tri[1][0] = BigInt.one for (i in 2...n) { tri[i][0] = tri[i-1][i-2] for (j in 1...i) { tri[i][j] = tri[i][j-1] + tri[i-1][j-1] } } return tri }   var bt = bellTriangle.call(51) System.print("First fifteen and fiftieth Bell numbers:") for (i in 1..15) Fmt.print("$2d: $,i", i, bt[i][0]) Fmt.print("$2d: $,i", 50, bt[50][0]) System.print("\nThe first ten rows of Bell's triangle:") for (i in 1..10) Fmt.print("$,7i", bt[i])
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Phix
Phix
with javascript_semantics function benford(sequence s, string title) sequence f = repeat(0,9) for i=1 to length(s) do integer fdx = sprint(s[i])[1]-'0' f[fdx] += 1 end for sequence res = {title,"Digit Observed% Predicted%"} for i=1 to length(f) do atom o = f[i]/length(s)*100, e = log10(1+1/i)*100 res = append(res,sprintf("  %d  %9.3f  %8.3f", {i, o, e})) end for return res end function function fib(integer lim) atom a=0, b=1 sequence res = repeat(0,lim) for i=1 to lim do {res[i], a, b} = {b, b, b+a} end for return res end function sequence res = {benford(fib(1000),"First 1000 Fibonacci numbers"), benford(get_primes(-10000),"First 10000 Prime numbers"), benford(sq_power(3,tagset(500)),"First 500 powers of three")} papply(true,printf,{1,{"%-40s%-40s%-40s\n"},columnize(res)})
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   +½.
#PARI.2FGP
PARI/GP
for(n=0,60,t=bernfrac(n);if(t,print(n" "t)))
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.
#E
E
/** Returns null if the value is not found. */ def binarySearch(collection, value) { var low := 0 var high := collection.size() - 1 while (low <= high) { def mid := (low + high) // 2 def comparison := value.op__cmp(collection[mid]) if (comparison.belowZero()) { high := mid - 1 } \ else if (comparison.aboveZero()) { low := mid + 1 } \ else if (comparison.isZero()) { return mid } \ else { throw("You expect me to binary search with a partial order?") } } return null }
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
#Phix
Phix
with javascript_semantics constant tests = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} for test=1 to length(tests) do string s = tests[test], t = shuffle(s) for i=1 to length(t) do for j=1 to length(t) do integer {ti,tj} = {t[i],t[j]} if i!=j and ti!=s[j] and tj!=s[i] then t[i] = tj t[j] = ti exit end if end for end for printf(1,"%s -> %s (%d)\n",{s,t,sum(sq_eq(t,s))}) end for
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.
#Ring
Ring
# string creation x = "hello world"   # string destruction x = NULL   # string assignment with a null byte x = "a"+char(0)+"b" see len(x) # ==> 3   # string comparison if x = "hello" See "equal" else See "not equal" ok y = 'bc' if strcmp(x,y) < 0 See x + " is lexicographically less than " + y ok   # string cloning xx = x See x = xx # true, same length and content   # check if empty if x = NULL See "is empty" ok   # append a byte x += char(7)   # substring x = "hello" x[1] = "H" See x + nl   # join strings a = "hel" b = "lo w" c = "orld" See a + b + c  
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.
#Ruby
Ruby
# string creation x = "hello world"   # string destruction x = nil   # string assignment with a null byte x = "a\0b" x.length # ==> 3   # string comparison if x == "hello" puts "equal" else puts "not equal" end y = 'bc' if x < y puts "#{x} is lexicographically less than #{y}" end   # string cloning xx = x.dup x == xx # true, same length and content x.equal?(xx) # false, different objects   # check if empty if x.empty? puts "is empty" end   # append a byte p x << "\07"   # substring p xx = x[0..-2] x[1,2] = "XYZ" p x   # replace bytes p y = "hello world".tr("l", "L")   # join strings a = "hel" b = "lo w" c = "orld" p d = a + b + c
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.
#C.23
C#
using System;   class Program { static void Main() { foreach (var number in new[] { 5, 50, 9000 }) { Console.WriteLine(Convert.ToString(number, 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.
#PureBasic
PureBasic
Procedure BresenhamLine(x0 ,y0 ,x1 ,y1) If Abs(y1 - y0) > Abs(x1 - x0); steep =#True Swap x0, y0 Swap x1, y1 EndIf If x0 > x1 Swap x0, x1 Swap y0, y1 EndIf deltax = x1 - x0 deltay = Abs(y1 - y0) error = deltax / 2 y = y0 If y0 < y1 ystep = 1 Else ystep = -1 EndIf For x = x0 To x1 If steep Plot(y,x) Else Plot(x,y) EndIf error - deltay If error < 0 y + ystep error + deltax EndIf Next EndProcedure   #Window1 = 0 #Image1 = 0 #ImgGadget = 0 #width = 300 #height = 300   Define.i Event Define.f Angle   If OpenWindow(#Window1, 0, 0, #width, #height, "Bresenham's Line PureBasic Example", #PB_Window_SystemMenu|#PB_Window_ScreenCentered) If CreateImage(#Image1, #width, #height) ImageGadget(#ImgGadget, 0, 0, #width, #height, ImageID(#Image1)) StartDrawing(ImageOutput(#Image1)) FillArea(0,0,-1,$FFFFFF) :FrontColor(0) While Angle < 2*#PI BresenhamLine(150,150,150+Cos(Angle)*120,150+Sin(Angle)*120) Angle + #PI/60 Wend   StopDrawing() SetGadgetState(#ImgGadget, ImageID(#Image1)) Repeat Event = WaitWindowEvent() Until Event = #PB_Event_CloseWindow EndIf EndIf
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
#XLISP
XLISP
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an attribute for its presence (empty or not), or whether a node set is empty. </xsl:if>
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
#XPL0
XPL0
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an attribute for its presence (empty or not), or whether a node set is empty. </xsl:if>
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)..
#Racket
Racket
#lang racket   ;;; Generate the headings and boxes (define (i->heading/box i) (values (let ((heading (* i #e11.25))) (case (modulo i 3) ((1) (+ heading #e5.62)) ((2) (- heading #e5.62)) (else heading))) (add1 (modulo i 32)))) (define-values (headings-list box-list) (for/lists (h-lst i-lst) ((i (in-range 0 (add1 32)))) (i->heading/box i)))   (define box-names (list "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"))   (define (heading->box h) (let* ((n-boxes (length box-names)) (box-width (/ 360 n-boxes))) (add1 (modulo (ceiling (- (/ h box-width) 1/2)) n-boxes))))   ;;; displays a single row of the table, can also be used for titles (define (display-row b a p) (printf "~a | ~a | ~a~%" (~a b #:width 2 #:align 'right) (~a a #:width 6 #:align 'right) (~a p)))   ;;; display the table (display-row "#" "Angle" "Point") (displayln "---+--------+-------------------") (for ((heading headings-list)) (let* ((box-number (heading->box heading)))  ;; by coincidence, default value of the second argument to  ;; real->decimal-string "decimal-digits" is 2,... just what we want! (display-row box-number (real->decimal-string heading) (list-ref box-names (sub1 box-number)))))   (module+ test (require rackunit)  ;;; unit test heading->box (the business end of the implementation) (check-= (heading->box 354.38) 1 0) (check-= (heading->box 5.62) 1 0) (check-= (heading->box 5.63) 2 0) (check-= (heading->box 16.87) 2 0))
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.
#Liberty_BASIC
Liberty BASIC
  ' bitwise operations on byte-sized variables   v =int( 256 *rnd( 1))   s = 1   print "Shift ="; s; " place." print print "Number as dec. = "; v; " & as 8-bits byte = ", dec2Bin$( v) print "NOT as dec. = "; bitInvert( v), dec2Bin$( bitInvert( v)) print "Shifted left as dec. = "; shiftLeft( v, s), dec2Bin$( shiftLeft( v, s)) print "Shifted right as dec. = "; shiftRight( v, s), dec2Bin$( shiftRight( v, s)) print "Rotated left as dec. = "; rotateLeft( v, s), dec2Bin$( rotateLeft( v, s)) print "Rotated right as dec. = "; rotateRight( v, s), dec2Bin$( rotateRight( v, s))   end   function shiftLeft( b, n) shiftLeft =( b *2^n) and 255 end function   function shiftRight( b, n) shiftRight =int(b /2^n) end function   function rotateLeft( b, n) rotateLeft = (( 2^n *b) mod 256) or ( b >127) end function   function rotateRight( b, n) rotateRight = (128*( b and 1)) or int( b /2) end function   function bitInvert( b) bitInvert =b xor 255 end function   function dec2Bin$( num) ' Given an integer decimal 0 <--> 255, returns binary equivalent as a string n =num dec2Bin$ ="" while ( num >0) dec2Bin$ =str$( num mod 2) +dec2Bin$ num =int( num /2) wend dec2Bin$ =right$( "00000000" +dec2Bin$, 8) end function  
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.
#PHP
PHP
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } //Fills a rectangle, or the whole image with black by default public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } }   $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); print_r($b->getPixel(3,3)); //(240,240,240)
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
#zkl
zkl
fcn bellTriangleW(start=1,wantRow=False){ // --> iterator Walker.zero().tweak('wrap(row){ row.insert(0,row[-1]); foreach i in ([1..row.len()-1]){ row[i]+=row[i-1] } wantRow and row or row[-1] }.fp(List(start))).push(start,start); }
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 .
#Picat
Picat
go =>   N = 1000, Fib = [fib(I) : I in 1..N], check_benford(Fib), nl.   % Check a list of numbers for Benford's law check_benford(L) => Len = L.len, println(len=Len), Count = [F[1].to_integer() : Num in L, F=Num.to_string()].occurrences(), P = new_map([I=D/Len : I=D in Count]), println("Benford (percent):"), foreach(D in 1..9) B = benford(D)*100, PI = P.get(D,0)*100, Diff = abs(PI - B), printf("%d: count=%5d observed: %0.2f%% Benford: %0.2f%% diff=%0.3f\n", D,Count.get(D,0),PI,B,Diff) end, nl.   benford(D) = log10(1+1/D).   % create an occurrences map of a list occurrences(List) = Map => Map = new_map(), foreach(E in List) Map.put(E, cond(Map.has_key(E),Map.get(E)+1,1)) end.
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#PicoLisp
PicoLisp
  (scl 4) (load "@lib/misc.l") (load "@lib/math.l")   (setq LOG10E 0.4343)   (de fibo (N) (let (A 0 B 1 C NIL) (make (link B) (do (dec N) (setq C (+ A B) A B B C) (link B)))))   (setq Actual (let ( Digits (sort (mapcar '((N) (format (car (chop N)))) (fibo 1000))) Count 0 ) (make (for (Ds Digits Ds (cdr Ds)) (inc 'Count) (when (n== (car Ds) (cadr Ds)) (link Count) (setq Count 0))))))   (setq Expected (mapcar '((D) (*/ (log (+ 1. (/ 1. D))) LOG10E 1.)) (range 1 9)))   (prinl "Digit\tActual\tExpected") (let (As Actual Bs Expected) (for D 9 (prinl D "\t" (format (pop 'As) 3) "\t" (round (pop 'Bs) 3))))   (bye)  
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   +½.
#Pascal
Pascal
  (* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *)   program BernoulliForAda99;   uses BigDecimalMath; {library for arbitary high precision BCD numbers}   type Fraction = object private numerator, denominator: BigDecimal;   public procedure assign(n, d: Int64); procedure subtract(rhs: Fraction); procedure multiply(value: Int64); procedure reduce(); procedure writeOutput(); end;     function gcd(a, b: BigDecimal):BigDecimal; begin if (b = 0) then begin gcd := a; end else begin gcd := gcd(b, a mod b); end; end;     procedure Fraction.writeOutput(); var sign : char; begin sign := ' '; if (numerator<0) then sign := '-'; if (denominator<0) then sign := '-'; write(sign + BigDecimalToStr(abs(numerator)):45); write(' / '); write(BigDecimalToStr(abs(denominator))); end;     procedure Fraction.assign(n, d: Int64); begin   numerator := n; denominator := d; end;     procedure Fraction.subtract(rhs: Fraction); begin numerator := numerator * rhs.denominator; numerator := numerator - (rhs.numerator * denominator); denominator := denominator * rhs.denominator; end;     procedure Fraction.multiply(value: Int64); var temp :BigDecimal; begin temp := value; numerator := numerator * temp; end;     procedure Fraction.reduce(); var gcdResult: BigDecimal; begin gcdResult := gcd(numerator, denominator); begin numerator := numerator div gcdResult; (* div is Int64 division *) denominator := denominator div gcdResult; (* could also use round(d/r) *) end; end;     function calculateBernoulli(n: Int64) : Fraction; var m, j: Int64; results: array of Fraction;   begin setlength(results, 60) ; {largest value 60} for m:= 0 to n do begin results[m].assign(1, m+1);   for j:= m downto 1 do begin results[j-1].subtract(results[j]); results[j-1].multiply(j); results[j-1].reduce(); end; end;   calculateBernoulli := results[0]; end;     (* Main program starts here *)   var b: Int64; result: Fraction;   begin writeln('Calculating Bernoulli numbers...'); writeln('B( 0) : 1 / 1'); for b:= 1 to 60 do begin if (b<3) or ((b mod 2) = 0) then begin result := calculateBernoulli(b); write('B(',b:2,')'); write(' : '); result.writeOutput(); writeln; end; end; 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.
#EasyLang
EasyLang
func bin_search val . a[] res . low = 0 high = len a[] - 1 res = -1 while low <= high and res = -1 mid = (low + high) div 2 if a[mid] > val high = mid - 1 elif a[mid] < val low = mid + 1 else res = mid . . . a[] = [ 2 4 6 8 9 ] call bin_search 8 a[] r print r
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
#PHP
PHP
foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w) echo bestShuffle($w) . '<br>';   function bestShuffle($s1) { $s2 = str_shuffle($s1); for ($i = 0; $i < strlen($s2); $i++) { if ($s2[$i] != $s1[$i]) continue; for ($j = 0; $j < strlen($s2); $j++) if ($i != $j && $s2[$i] != $s1[$j] && $s2[$j] != $s1[$i]) { $t = $s2[$i]; $s2[$i] = $s2[$j]; $s2[$j] = $t; break; } } return "$s1 $s2 " . countSame($s1, $s2); }   function countSame($s1, $s2) { $cnt = 0; for ($i = 0; $i < strlen($s2); $i++) if ($s1[$i] == $s2[$i]) $cnt++; return "($cnt)"; }
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.
#Run_BASIC
Run BASIC
' Create string s$ = "Hello, world"   ' String destruction s$ = ""   ' String comparison If s$ = "Hello, world" then print "Equal String"   ' Copying string a$ = s$   ' Check If empty If s$ = "" then print "String is MT"   ' Append a byte s$ = s$ + Chr$(65)   ' Extract a substring a$ = Mid$(s$, 1, 5) ' bytes 1 -> 5   'substitute string "world" with "universe" a$ = "Hello, world" for i = 1 to len(a$) if mid$(a$,i,5)="world" then a$=left$(a$,i-1)+"universe"+mid$(a$,i+5) end if next print a$   'join strings s$ = "See " + "you " + "later." print s$
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.
#Rust
Rust
use std::str;   fn main() { // Create new string let string = String::from("Hello world!"); println!("{}", string); assert_eq!(string, "Hello world!", "Incorrect string text");   // Create and assign value to string let mut assigned_str = String::new(); assert_eq!(assigned_str, "", "Incorrect string creation"); assigned_str += "Text has been assigned!"; println!("{}", assigned_str); assert_eq!(assigned_str, "Text has been assigned!","Incorrect string text");   // String comparison, compared lexicographically byte-wise same as the asserts above if string == "Hello world!" && assigned_str == "Text has been assigned!" { println!("Strings are equal"); }   // Cloning -> string can still be used after cloning let clone_str = string.clone(); println!("String is:{} and Clone string is: {}", string, clone_str); assert_eq!(clone_str, string, "Incorrect string creation");   // Copying, string won't be usable anymore, accessing it will cause compiler failure let copy_str = string; println!("String copied now: {}", copy_str);   // Check if string is empty let empty_str = String::new(); assert!(empty_str.is_empty(), "Error, string should be empty");   // Append byte, Rust strings are a stream of UTF-8 bytes let byte_vec = [65]; // contains A let byte_str = str::from_utf8(&byte_vec).unwrap(); assert_eq!(byte_str, "A", "Incorrect byte append");   // Substrings can be accessed through slices let test_str = "Blah String"; let mut sub_str = &test_str[0..11]; assert_eq!(sub_str, "Blah String", "Error in slicing"); sub_str = &test_str[1..5]; assert_eq!(sub_str, "lah ", "Error in slicing"); sub_str = &test_str[3..]; assert_eq!(sub_str, "h String", "Error in slicing"); sub_str = &test_str[..2]; assert_eq!(sub_str, "Bl", "Error in slicing");   // String replace, note string is immutable let org_str = "Hello"; assert_eq!(org_str.replace("l", "a"), "Heaao", "Error in replacement"); assert_eq!(org_str.replace("ll", "r"), "Hero", "Error in replacement");   // Joining strings requires a `String` and an &str or a two `String`s one of which needs an & for coercion let str1 = "Hi"; let str2 = " There"; let fin_str = str1.to_string() + str2; assert_eq!(fin_str, "Hi There", "Error in concatenation");   // Joining strings requires a `String` and an &str or two `Strings`s, one of which needs an & for coercion let str1 = "Hi"; let str2 = " There"; let fin_str = str1.to_string() + str2; assert_eq!(fin_str, "Hi There", "Error in concatenation");   // Splits -- note Rust supports passing patterns to splits let f_str = "Pooja and Sundar are up in Tumkur"; let split_str: Vec<_> = f_str.split(' ').collect(); assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split"); }
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.
#C.2B.2B
C++
#include <bitset> #include <iostream> #include <limits> #include <string>   void print_bin(unsigned int n) { std::string str = "0";   if (n > 0) { str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string(); str = str.substr(str.find('1')); // remove leading zeros }   std::cout << str << '\n'; }   int main() { print_bin(0); print_bin(5); print_bin(50); print_bin(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.
#Python
Python
def line(self, x0, y0, x1, y1): "Bresenham's line algorithm" dx = abs(x1 - x0) dy = abs(y1 - y0) x, y = x0, y0 sx = -1 if x0 > x1 else 1 sy = -1 if y0 > y1 else 1 if dx > dy: err = dx / 2.0 while x != x1: self.set(x, y) err -= dy if err < 0: y += sy err += dx x += sx else: err = dy / 2.0 while y != y1: self.set(x, y) err -= dx if err < 0: x += sx err += dy y += sy self.set(x, y) Bitmap.line = line   bitmap = Bitmap(17,17) for points in ((1,8,8,16),(8,16,16,8),(16,8,8,1),(8,1,1,8)): bitmap.line(*points) bitmap.chardisplay()   ''' The origin, 0,0; is the lower left, with x increasing to the right, and Y increasing upwards.   The chardisplay above produces the following output : +-----------------+ | @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @| | @ @ | | @ @ | | @ @@ | | @ @ | | @ @ | | @ @ | | @ | | | +-----------------+ '''
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
#XSLT
XSLT
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an attribute for its presence (empty or not), or whether a node set is empty. </xsl:if>
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
#Z80_Assembly
Z80 Assembly
BIT 0,A jr nz,true ;;;;;;;;;;;;;;;; AND 1 jr nz,true ;;;;;;;;;;;;;;;; RRCA jr c,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
#zkl
zkl
a:=True; b:=False; True.dir();
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)..
#Raku
Raku
sub point (Int $index) { my $ix = $index % 32; if $ix +& 1 { "&point(($ix + 1) +& 28) by &point(((2 - ($ix +& 2)) * 4) + $ix +& 24)" } elsif $ix +& 2 { "&point(($ix + 2) +& 24)-&point(($ix +| 4) +& 28)" } elsif $ix +& 4 { "&point(($ix + 8) +& 16)&point(($ix +| 8) +& 24)" } else { <north east south west>[$ix div 8]; } }   sub test-angle ($ix) { $ix * 11.25 + (0, 5.62, -5.62)[ $ix % 3 ] } sub angle-to-point(\𝜽) { floor 𝜽 / 360 * 32 + 0.5 }   for 0 .. 32 -> $ix { my \𝜽 = test-angle($ix); printf "  %2d %6.2f° %s\n", $ix % 32 + 1, 𝜽, tc point angle-to-point 𝜽; }
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.
#Lingo
Lingo
put bitAND(2,7) put bitOR(2,7) put bitXOR(2,7) put bitNOT(7)
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#PicoLisp
PicoLisp
# Create an empty image of 120 x 90 pixels (setq *Ppm (make (do 90 (link (need 120)))))   # Fill an image with a given color (de ppmFill (Ppm R G B) (for Y Ppm (map '((X) (set X (list R G B))) Y ) ) )   # Set pixel with a color (de ppmSetPixel (Ppm X Y R G B) (set (nth Ppm Y X) (list R G B)) )   # Get the color of a pixel (de ppmGetPixel (Ppm X Y) (get Ppm Y X) )
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.
#PL.2FI
PL/I
  /* Declaration for an image, suitable for BMP files. */ declare image(0:500, 0:500) bit (24) aligned;   image = '000000000000000011111111'b; /* Sets the entire image to red. */   image(10,40) = '111111110000000000000000'b; /* Sets one pixel to blue. */   declare color bit (24) aligned; color = image(20,50); /* Obtain the color of a pixel */       /* To allocate an image of size (x,y) */ allocate_image: procedure (image, x, y); declare image (*, *) controlled bit (24) aligned; declare (x, y) fixed binary (31);   allocate image (0:x, 0:y); end allocate_image;   /* To use the above procedure, it's necessary to define */ /* the image in the calling program thus, for BMP images: */   declare image(*,*) controlled bit (24) aligned;  
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 .
#PL.2FI
PL/I
  (fofl, size, subrg): Benford: procedure options(main); /* 20 October 2013 */ declare sc(1000) char(1), f(1000) float (16); declare d fixed (1);   call Fibonacci(f); call digits(sc, f);   put skip list ('digit expected obtained'); do d= 1 upthru 9; put skip edit (d, log10(1 + 1/d), tally(sc, trim(d))/1000) (f(3), 2 f(13,8) ); end;   Fibonacci: procedure (f); declare f(*) float (16); declare i fixed binary;   f(1), f(2) = 1; do i = 3 to 1000; f(i) = f(i-1) + f(i-2); end; end Fibonacci;   digits: procedure (sc, f); declare sc(*) char(1), f(*) float (16); sc = substr(trim(f), 1, 1); end digits;   tally: procedure (sc, d) returns (fixed binary); declare sc(*) char(1), d char(1); declare (i, t) fixed binary; t = 0; do i = 1 to 1000; if sc(i) = d then t = t + 1; end; return (t); end tally; end Benford;  
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 .
#PL.2FpgSQL
PL/pgSQL
  WITH recursive constant(val) AS ( SELECT 1000. ) , fib(a,b) AS ( SELECT CAST(0 AS NUMERIC), CAST(1 AS NUMERIC) UNION ALL SELECT b,a+b FROM fib ) , benford(first_digit, probability_real, probability_theoretical) AS ( SELECT *, CAST(log(1. + 1./CAST(first_digit AS INT)) AS NUMERIC(5,4)) probability_theoretical FROM ( SELECT first_digit, CAST(COUNT(1)/(SELECT val FROM constant) AS NUMERIC(5,4)) probability_real FROM ( SELECT SUBSTRING(CAST(a AS VARCHAR(100)),1,1) first_digit FROM fib WHERE SUBSTRING(CAST(a AS VARCHAR(100)),1,1) <> '0' LIMIT (SELECT val FROM constant) ) t GROUP BY first_digit ) f ORDER BY first_digit ASC ) SELECT * FROM benford CROSS JOIN (SELECT CAST(corr(probability_theoretical,probability_real) AS NUMERIC(5,4)) correlation FROM benford) c  
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   +½.
#Perl
Perl
#!perl use strict; use warnings; use List::Util qw(max); use Math::BigRat;   my $one = Math::BigRat->new(1); sub bernoulli_print { my @a; for my $m ( 0 .. 60 ) { push @a, $one / ($m + 1); for my $j ( reverse 1 .. $m ) { # This line: ( $a[$j-1] -= $a[$j] ) *= $j; # is a faster version of the following line: # $a[$j-1] = $j * ($a[$j-1] - $a[$j]); # since it avoids unnecessary object creation. } next unless $a[0]; printf "B(%2d) = %44s/%s\n", $m, $a[0]->parts; } }   bernoulli_print();  
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.
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make local a: ARRAY [INTEGER] keys: ARRAY [INTEGER] do a := <<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>> keys := <<0, 42, 45, 24324, 99999>> across keys as k loop if has_binary (a, k.item) then print ("The array has an element " + k.item.out) else print ("The array has NOT an element " + k.item.out) end print ("%N") end end   feature -- Search   has_binary (a: ARRAY [INTEGER]; key: INTEGER): BOOLEAN -- Does `a[a.lower..a.upper]' include an element `key'? require is_sorted (a, a.lower, a.upper) local i: INTEGER do i := where_binary (a, key) if a.lower <= i and i <= a.upper then Result := True else Result := False end end   where_binary (a: ARRAY [INTEGER]; key: INTEGER): INTEGER -- The index of an element `key' within `a[a.lower..a.upper]' if it exists. -- Otherwise an integer outside `[a.lower..a.upper]' require is_sorted (a, a.lower, a.upper) do Result := where_binary_range (a, key, a.lower, a.upper) end   where_binary_range (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): INTEGER -- The index of an element `key' within `a[low..high]' if it exists. -- Otherwise an integer outside `[low..high]' note source: "http://arxiv.org/abs/1211.4470" require is_sorted (a, low, high) local i, j, mid: INTEGER do if low > high then Result := low - 1 else from i := low j := high mid := low Result := low - 1 invariant low <= i and i <= mid + 1 low <= mid and mid <= j and j <= high i <= j has (a, key, i, j) = has (a, key, low, high) until i >= j loop mid := i + (j - i) // 2 if a [mid] < key then i := mid + 1 else j := mid end variant j - i end if a [i] = key then Result := i end end ensure low <= Result and Result <= high implies a [Result] = key Result < low or Result > high implies not has (a, key, low, high) end   feature -- Implementation   is_sorted (a: ARRAY [INTEGER]; low, high: INTEGER): BOOLEAN -- Is `a[low..high]' sorted in nondecreasing order? require a.lower <= low high <= a.upper do Result := across low |..| (high - 1) as i all a [i.item] <= a [i.item + 1] end end   has (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): BOOLEAN -- Is there an element `key' in `a[low..high]'? require a.lower <= low high <= a.upper do Result := across low |..| high as i some a [i.item] = key end end   end
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Picat
Picat
import cp.   go => Words = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "shuffle", "aaaaaaa" ], foreach(Word in Words) best_shuffle(Word,Best,_Score), printf("%s, %s, (%d)\n", Word,Best,diff_word(Word, Best)) end, nl.   best_shuffle(Word,Best,Score) => WordAlpha = Word.map(ord), % convert to integers WordAlphaNoDups = WordAlpha.remove_dups(),  % occurrences of each character in the word Occurrences = occurrences(WordAlpha),   Len = Word.length,    % Decision variables WordC = new_list(Len), WordC :: WordAlphaNoDups,    %  % The constraints  %    % Ensure that the shuffled word has the same  % occurrences for each character foreach(V in WordAlphaNoDups) count(V, WordC,#=, Occurrences.get(V)) end,    % The score is the number of characters  % in the same position as the origin word  % (to be minimized). Score #= sum([WordC[I] #= WordAlpha[I] : I in 1..Len]),   if var(Score) then  % We don't have a score yet: minimize Score solve([$min(Score),split], WordC) else  % Get a solution for the given Score solve([split], WordC) end,  % convert back to alpha Best = WordC.map(chr).     diff_word(W1,W2) = Diff => Diff = sum([1 : I in 1..W1.length, W1[I]==W2[I]]).   occurrences(L) = Occ => Occ = new_map(), foreach(E in L) Occ.put(E, Occ.get(E,0) + 1) 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.
#Seed7
Seed7
var string: stri is "asdf"; # variable declaration const string: stri is "jkl"; # constant declaration
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.
#Smalltalk
Smalltalk
s := "abc" # create a string (immutable if its a literal constant in the program) s := #[16r01 16r02 16r00 16r03] asString # strings can contain any value, even nulls s := String new:3. # a mutable string v := s # assignment s = t # same contents s < t # less s <= t # less or equal s = '' # equal empty string s isEmpty # ditto s size # string length t := s copy # a copy t := s copyFrom:2 to:3 # a substring t := s copyReplaceFrom:2 to:3 with:'**' # a copy with some replacements s replaceFrom:2 to:3 with:'**' # inplace replace (must be mutable) s replaceAll:$x with:$y # destructive replace of characters s copyReplaceAll:$x with:$y # non-destructive replace s replaceString:s1 withString:s2 # substring replace s3 := s1 , s2 # concatenation of strings s2 := s1 , $x # append a character s2 := s1 , 123 asCharacter # append an arbitrary byte s := 'Hello / 今日は' # they support unicode (at least up to 16rFFFF, some more)
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.
#Ceylon
Ceylon
shared void run() {   void printBinary(Integer integer) => print(Integer.format(integer, 2));   printBinary(5); printBinary(50); printBinary(9k); }
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.
#Racket
Racket
  #lang racket (require racket/draw)   (define (draw-line dc x0 y0 x1 y1) (define dx (abs (- x1 x0))) (define dy (abs (- y1 y0))) (define sx (if (> x0 x1) -1 1)) (define sy (if (> y0 y1) -1 1)) (cond [(> dx dy) (let loop ([x x0] [y y0] [err (/ dx 2.0)]) (unless (= x x1) (send dc draw-point x y) (define newerr (- err dy)) (if (< newerr 0) (loop (+ x sx) (+ y sy) (+ newerr dx)) (loop (+ x sx) y newerr))))] [else (let loop ([x x0] [y y0] [err (/ dy 2.0)]) (unless (= y y1) (send dc draw-point x y) (define newerr (- err dy)) (if (< newerr 0) (loop (+ x sx) (+ y sy) newerr) (loop x (+ y sy) (+ newerr dy)))))]))   (define bm (make-object bitmap% 17 17)) (define dc (new bitmap-dc% [bitmap bm])) (send dc set-smoothing 'unsmoothed) (send dc set-pen "red" 1 'solid) (for ([points '((1 8 8 16) (8 16 16 8) (16 8 8 1) (8 1 1 8))]) (apply draw-line (cons dc points))) bm  
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
#zonnon
zonnon
    var a,b,c: boolean; begin a := false; b := true; c := 1 > 2; ...  
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)..
#Red
Red
Red []   d: charset [#"N" #"E" #"S" #"W"] ;; main directions hm: #() ;; hm = hashmap - key= heading, value = [box , compass point]   compass-points: [N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW N ]   expand: func [cp repl][ ;; expand compass point to words parse cp [ copy a thru d ahead 2 d insert "-" ] ;; insert "-" after first direction, if followed by 2 more foreach [src dst ] repl [ replace/all cp to-string src to-string dst ] ;; N -> north ... uppercase/part cp 1 ;; convert first letter to uppercase ]   print-line: does [ print [pad/left hm/:heading/1 3 pad hm/:heading/2 20 heading ] ]   forall compass-points [ i: (index? compass-points) - 1 ;; so i = 0..33 heading: i * 11.25 + either 1 = rem: i % 3 [ 5.62] ;; rem = remainder [ either rem = 2 [-5.62] [0.0] ] hm/:heading: reduce [ (i % 32 + 1 ) expand to-string compass-points/1 [N north b " by " S south E east W west] ] print-line heading ]
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.
#LiveCode
LiveCode
put "and:" && (255 bitand 2) & comma into bitops put " or:" && (255 bitor 2) & comma after bitops put " xor:" && (255 bitxor 2) & comma after bitops put " not:" && (bitnot 255) after bitops put bitops   -- Ouput and: 2, or: 255, xor: 253, not: 4294967040
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.
#Processing
Processing
PGraphics bitmap = createGraphics(100,100); // Create the bitmap bitmap.beginDraw(); bitmap.background(255, 0, 0); // Fill bitmap with red rgb color bitmap.endDraw(); image(bitmap, 0, 0); // Place bitmap on screen. color b = color(0, 0, 255); // Define a blue rgb color set(50, 50, b); // Set blue colored pixel in the middle of the screen color c = get(50, 50); // Get the color of same pixel if(b == c) print("Color changed correctly"); // Verify  
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 .
#PowerShell
PowerShell
  $url = "https://oeis.org/A000045/b000045.txt" $file = "$env:TEMP\FibonacciNumbers.txt" (New-Object System.Net.WebClient).DownloadFile($url, $file)   $benford = Get-Content -Path $file | Select-Object -Skip 1 -First 1000 | ForEach-Object {(($_ -split " ")[1].ToString().ToCharArray())[0]} | Group-Object | Select-Object -Property @{Name="Digit"  ; Expression={[int]($_.Name)}}, Count, @{Name="Actual"  ; Expression={$_.Count/1000}}, @{Name="Expected"; Expression={[double]("{0:f5}" -f [Math]::Log10(1 + 1 / $_.Name))}}   $benford | Sort-Object -Property Digit | Format-Table -AutoSize   Remove-Item -Path $file -Force -ErrorAction SilentlyContinue  
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   +½.
#Phix
Phix
with javascript_semantics include builtins/mpfr.e procedure bernoulli(mpq rop, integer n) sequence a = mpq_inits(n+1) for m=1 to n+1 do mpq_set_si(a[m], 1, m) for j=m-1 to 1 by -1 do mpq_sub(a[j], a[j+1], a[j]) mpq_set_si(rop, j, 1) mpq_mul(a[j], a[j], rop) end for end for mpq_set(rop, a[1]) a = mpq_free(a) end procedure mpq rop = mpq_init() mpz n = mpz_init(), d = mpz_init() for i=0 to 60 do bernoulli(rop, i) if mpq_cmp_si(rop, 0, 1) then mpq_get_num(n, rop) mpq_get_den(d, rop) string ns = mpz_get_str(n), ds = mpz_get_str(d) printf(1,"B(%2d) = %44s / %s\n", {i,ns,ds}) end if end for {n,d} = mpz_free({n,d}) rop = mpq_free(rop)
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.
#Elixir
Elixir
defmodule Binary do def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)   def search(_tuple, _value, low, high) when high < low, do: :not_found def search(tuple, value, low, high) do mid = div(low + high, 2) midval = elem(tuple, mid) cond do value < midval -> search(tuple, value, low, mid-1) value > midval -> search(tuple, value, mid+1, high) value == midval -> mid end end end   list = [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] Enum.each([0,42,45,24324,99999], fn val -> case Binary.search(list, val) do  :not_found -> IO.puts "#{val} not found in list" index -> IO.puts "found #{val} at index #{index}" end end)
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(de bestShuffle (Str) (let Lst NIL (for C (setq Str (chop Str)) (if (assoc C Lst) (con @ (cons C (cdr @))) (push 'Lst (cons C)) ) ) (setq Lst (apply conc (flip (by length sort Lst)))) (let Res (mapcar '((C) (prog1 (or (find <> Lst (circ C)) C) (setq Lst (delete @ Lst)) ) ) Str ) (prinl Str " " Res " (" (cnt = Str Res) ")") ) ) )
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
#PL.2FI
PL/I
shuffle: procedure options (main); /* 14/1/2011 */ declare (s, saves) character (20) varying, c character (1); declare t(length(s)) bit (1); declare (i, k, moves initial (0)) fixed binary;   get edit (s) (L); put skip list (s); saves = s; t = '0'b; do i = 1 to length (s); if t(i) then iterate; /* This character has already been moved. */ c = substr(s, i, 1); k = search (s, c, i+1); if k > 0 then do; substr(s, i, 1) = substr(s, k, 1); substr(s, k, 1) = c; t(k), t(i) = '1'b; end; end;   do k = length(s) to 2 by -1; if ^t(k) then /* this character wasn't moved. */ all: do; c = substr(s, k, 1); do i = k-1 to 1 by -1; if c ^= substr(s, i, 1) then if substr(saves, i, 1) ^= c then do; substr(s, k, 1) = substr(s, i, 1); substr(s, i, 1) = c; t(k) = '1'b; leave all; end; end; end; end; moves = length(s) - sum(t); put skip edit (s, trim(moves))(a, x(1));   search: procedure (s, c, k) returns (fixed binary); declare s character (*) varying; declare c character (1); declare k fixed binary; declare i fixed binary;   do i = k to length(s); if ^t(i) then if c ^= substr(s, i, 1) then return (i); end; return (0); /* No eligible character. */ end search;   end shuffle;
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.
#Tcl
Tcl
# string creation set x "hello world"   # string destruction unset x   # string assignment with a null byte set x a\0b string length $x ;# ==> 3   # string comparison if {$x eq "hello"} {puts equal} else {puts "not equal"} set y bc if {$x < $y} {puts "$x is lexicographically less than $y"}   # string copying; cloning happens automatically behind the scenes set xx $x   # check if empty if {$x eq ""} {puts "is empty"} if {[string length $x] == 0} {puts "is empty"}   # append a byte append x \07   # substring set xx [string range $x 0 end-1]   # replace bytes set y [string map {l L} "hello world"]   # join strings set a "hel" set b "lo w" set c "orld" set d $a$b$c
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.
#Clojure
Clojure
(Integer/toBinaryString 5) (Integer/toBinaryString 50) (Integer/toBinaryString 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.
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @!data;   method fill(Pixel $p) { @!data = $p.clone xx ($!width*$!height) } method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] }   method set-pixel ($i, $j, Pixel $p) { self.pixel($i, $j) = $p.clone; } method get-pixel ($i, $j) returns Pixel { self.pixel($i, $j); } }   sub line(Bitmap $bitmap, $x0 is copy, $x1 is copy, $y0 is copy, $y1 is copy) { my $steep = abs($y1 - $y0) > abs($x1 - $x0); if $steep { ($x0, $y0) = ($y0, $x0); ($x1, $y1) = ($y1, $x1); } if $x0 > $x1 { ($x0, $x1) = ($x1, $x0); ($y0, $y1) = ($y1, $y0); } my $Δx = $x1 - $x0; my $Δy = abs($y1 - $y0); my $error = 0; my $Δerror = $Δy / $Δx; my $y-step = $y0 < $y1 ?? 1 !! -1; my $y = $y0; for $x0 .. $x1 -> $x { my $pix = Pixel.new(R => 100, G => 200, B => 0); if $steep { $bitmap.set-pixel($y, $x, $pix); } else { $bitmap.set-pixel($x, $y, $pix); } $error += $Δerror; if $error >= 0.5 { $y += $y-step; $error -= 1.0; } } }
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)..
#REXX
REXX
/*REXX program "boxes the compass" [from degree (º) headings ───► a 32 point set]. */ parse arg $ /*allow º headings to be specified.*/ if $='' then $= 0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25 118.12 118.13 , 135 151.87 151.88 168.75 185.62 185.63 202.5 219.37 219.38 236.25 , 253.12 253.13 270 286.87 286.88 303.75 320.62 320.63 337.5 354.37 354.38 /* [↑] use default, they're in degrees*/ @pts= '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"   #= words(@pts) + 1 /*#: used for integer ÷ remainder (//)*/ dirs= 'north south east west' /*define cardinal compass directions. */ /* [↓] choose a glyph for degree (°).*/ if 4=='f4'x then degSym= "a1"x /*is this system an EBCDIC system? */ else degSym= "a7"x /*'f8'x is the degree symbol: ° vs º */ /*──────────────────────────── f8 vs a7*/ say right(degSym'heading', 30) center("compass heading", 20) say right( '════════', 30) copies( "═", 20) pad= ' ' /*used to interject a blank for output.*/ do j=1 for words($); x= word($, j) /*obtain one of the degree headings. */ say right( format(x, , 2)degSym, 30-1) pad boxHeading(x) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ boxHeading: y= arg(1)//360; if y<0 then y=360-y /*normalize heading within unit circle.*/ z= word(@pts, trunc(max(1, (y/11.25 +1.5) // #))) /*convert degrees─►heading*/ do k=1 for words(dirs); d= word(dirs, k) z= changestr( left(d, 1), z, d) end /*k*/ /* [↑] old, haystack, new*/ return changestr('b', z, " by ") /*expand "b" ───► " by ".*/
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.
#LLVM
LLVM
; ModuleID = 'test.o' ;e means little endian ;p: { pointer size : pointer abi : preferred alignment for pointers } ;i same for integers ;v is for vectors ;f for floats ;a for aggregate types ;s for stack objects ;n: {size:size:size...}, best integer sizes target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32" ;this was compiled with mingw32; thus it must be linked to an ABI compatible c library target triple = "i386-mingw32"   @.str = private constant [13 x i8] c"a and b: %d\0A\00", align 1 ; <[13 x i8]*> [#uses=1] @.str1 = private constant [12 x i8] c"a or b: %d\0A\00", align 1 ; <[12 x i8]*> [#uses=1] @.str2 = private constant [13 x i8] c"a xor b: %d\0A\00", align 1 ; <[13 x i8]*> [#uses=1] @.str3 = private constant [11 x i8] c"not a: %d\0A\00", align 1 ; <[11 x i8]*> [#uses=1] @.str4 = private constant [12 x i8] c"a << n: %d\0A\00", align 1 ; <[12 x i8]*> [#uses=1] @.str5 = private constant [12 x i8] c"a >> n: %d\0A\00", align 1 ; <[12 x i8]*> [#uses=1] @.str6 = private constant [12 x i8] c"c >> b: %d\0A\00", align 1 ; <[12 x i8]*> [#uses=1]   ;A function that will do many bitwise opreations to two integer arguments, %a and %b define void @bitwise(i32 %a, i32 %b) nounwind { ;entry block entry: ;Register to store (a & b) %0 = and i32 %b, %a ; <i32> [#uses=1] ;print the results %1 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([13 x i8]* @.str, i32 0, i32 0), i32 %0) nounwind ; <i32> [#uses=0] ;Register to store (a | b) %2 = or i32 %b, %a ; <i32> [#uses=1] ;print the results %3 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([12 x i8]* @.str1, i32 0, i32 0), i32 %2) nounwind ; <i32> [#uses=0] ;Register to store (a ^ b) %4 = xor i32 %b, %a ; <i32> [#uses=1] ;print the results %5 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([13 x i8]* @.str2, i32 0, i32 0), i32 %4) nounwind ; <i32> [#uses=0] ;Register to store (~a) %not = xor i32 %a, -1 ; <i32> [#uses=1] ;print the results %6 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([11 x i8]* @.str3, i32 0, i32 0), i32 %not) nounwind ; <i32> [#uses=0] ;Register to store (a << b) %7 = shl i32 %a, %b ; <i32> [#uses=1] ;print the results %8 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([12 x i8]* @.str4, i32 0, i32 0), i32 %7) nounwind ; <i32> [#uses=0] ;Register to store (a >> b) (a is signed) %9 = ashr i32 %a, %b ; <i32> [#uses=1] ;print the results %10 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([12 x i8]* @.str5, i32 0, i32 0), i32 %9) nounwind ; <i32> [#uses=0] ;Register to store (c >> b), where c is unsiged (eg. logical right shift) %11 = lshr i32 %a, %b ; <i32> [#uses=1] ;print the results %12 = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([12 x i8]* @.str6, i32 0, i32 0), i32 %11) nounwind ; <i32> [#uses=0]   ;terminator instruction ret void }   ;Declare external fuctions declare i32 @printf(i8* nocapture, ...) nounwind
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.
#Prolog
Prolog
  :- module(bitmap, [ new_bitmap/3, fill_bitmap/3, get_pixel0/3, set_pixel0/4 ]).   :- use_module(library(lists)).   %-----------------------------------------------------------------------------% % Convenience Predicates replicate(Term,Times,L):- length(L,Times), maplist(=(Term),L).   replace0(N,OL,E,NL):- nth0(N,OL,_,TL), nth0(N,NL,E,TL). %-----------------------------------------------------------------------------% % Bitmap Utilities % % The Bitmap structure is a list with pixels kept in row major order: % [dimensions-[X,Y],pixels-[[n11,n12...],[n21,n22...]]]   % In this code what exactly an RGB value is doesn't matter however % in other bitmap tasks it is assumed to be a list [R,G,B] where % each is an int between 0 and 255, in code: rgb_pixel(RGB):- length(RGB,3), maplist(integer,RGB), maplist(between(0,255),RGB).   %new_bitmap(Bitmap,Dimensions,RGB) new_bitmap([[X,Y],Pixels],[X,Y],RGB) :- replicate(RGB,X,Row), replicate(Row,Y,Pixels).   %fill_bitmap(New_Bitmap,Bitmap,RGB) fill_bitmap(New_Bitmap,[[X,Y],_],RGB) :- new_bitmap(New_Bitmap,[X,Y],RGB).   %here get and set use 0 based indexing %get_pixel0(Bitmap,Coordinates,RGB) get_pixel0([[_DimX,_DimY],Pixels],[X,Y],RGB) :- nth0(Y,Pixels,Row), nth0(X,Row,RGB).   %set_pixel0(New Bitmap, Bitmap, Coordinates, RGB) set_pixel0([[DimX,DimY],New_Pixels],[[DimX,DimY],Pixels],[X,Y],RGB) :- nth0(Y,Pixels,Row), replace0(X,Row,RGB,New_Row), replace0(Y,Pixels,New_Row,New_Pixels).  
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 .
#Prolog
Prolog
%_________________________________________________________________ % Does the Fibonacci sequence follow Benford's law? %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % Fibonacci sequence generator fib(C, [P,S], C, N) :- N is P + S. fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], Cv, V).   fib(0, 0). fib(1, 1). fib(C, N) :- fib(2, [0,1], C, N). % Generate from 3rd sequence on   % The benford law calculated benford(D, Val) :- Val is log10(1+1/D).   % Retrieves the first characters of the first 1000 fibonacci numbers % (excluding zero) firstchar(V) :- fib(C,N), N =\= 0, atom_chars(N, [Ch|_]), number_chars(V, [Ch]), (C>999-> !; true).   % Increment the n'th list item (1 based), result -> third argument. incNth(1, [Dh|Dt], [Ch|Dt]) :- !, succ(Dh, Ch). incNth(H, [Dh|Dt], [Dh|Ct]) :- succ(Hn, H), !, incNth(Hn, Dt, Ct).   % Calculate the frequency of the all the list items freq([], D, D). freq([H|T], D, C) :- incNth(H, D, L), !, freq(T, L, C).   freq([H|T], Freq) :- length([H|T], Len), min_list([H|T], Min), max_list([H|T], Max), findall(0, between(Min,Max,_), In), freq([H|T], In, F), % Frequency stored in F findall(N, (member(V, F), N is V/Len), Freq). % Normalise F->Freq   % Output the results writeHdr :- format('~t~w~15| - ~t~w\n', ['Benford', 'Measured']). writeData(Benford, Freq) :- format('~t~2f%~15| - ~t~2f%\n', [Benford*100, Freq*100]).   go :- % main goal findall(B, (between(1,9,N), benford(N,B)), Benford), findall(C, firstchar(C), Fc), freq(Fc, Freq), writeHdr, maplist(writeData, Benford, Freq).
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   +½.
#PicoLisp
PicoLisp
(load "@lib/frac.l")   (de fact (N) (cache '(NIL) N (if (=0 N) 1 (apply * (range 1 N))) ) )   (de binomial (N K) (frac (/ (fact N) (* (fact (- N K)) (fact K)) ) 1 ) )   (de A (N M) (let Sum (0 . 1) (for X M (setq Sum (f+ Sum (f* (binomial (+ N 3) (- N (* X 6))) (berno (- N (* X 6)) ) ) ) ) ) Sum ) )   (de berno (N) (cache '(NIL) N (cond ((=0 N) (1 . 1)) ((= 1 N) (-1 . 2)) ((bit? 1 N) (0 . 1)) (T (case (% N 6) (0 (f/ (f- (frac (+ N 3) 3) (A N (/ N 6)) ) (binomial (+ N 3) N) ) ) (2 (f/ (f- (frac (+ N 3) 3) (A N (/ (- N 2) 6)) ) (binomial (+ N 3) N) ) ) (4 (f/ (f- (f* (-1 . 1) (frac (+ N 3) 6)) (A N (/ (- N 4) 6)) ) (binomial (+ N 3) N) ) ) ) ) ) ) )   (de berno-brute (N) (cache '(NIL) N (let Sum (0 . 1) (cond ((=0 N) (1 . 1)) ((= 1 N) (-1 . 2)) ((bit? 1 N) (0 . 1)) (T (for (X 0 (> N X) (inc X)) (setq Sum (f+ Sum (f* (binomial (inc N) X) (berno-brute X)) ) ) ) (f/ (f* (-1 . 1) Sum) (binomial (inc N) N)) ) ) ) ) )   (for (N 0 (> 62 N) (inc N)) (if (or (= N 1) (not (bit? 1 N))) (tab (2 4 -60) N " => " (sym (berno N))) ) )   (for (N 0 (> 400 N) (inc N)) (test (berno N) (berno-brute N)) )   (bye)
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.
#Emacs_Lisp
Emacs Lisp
  (defun binary-search (value array) (let ((low 0) (high (1- (length array)))) (cl-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 (cl-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
#PowerShell
PowerShell
# Calculate best possible shuffle score for a given string # (Split out into separate function so we can use it separately in our output) function Get-BestScore ( [string]$String ) { # Convert to array of characters, group identical characters, # sort by frequecy, get size of first group $MostRepeats = $String.ToCharArray() | Group | Sort Count -Descending | Select -First 1 -ExpandProperty Count   # Return count of most repeated character minus all other characters (math simplified) return [math]::Max( 0, 2 * $MostRepeats - $String.Length ) }   function Get-BestShuffle ( [string]$String ) { # Convert to arrays of characters, one for comparison, one for manipulation $S1 = $String.ToCharArray() $S2 = $String.ToCharArray()   # Calculate best possible score as our goal $BestScore = Get-BestScore $String   # Unshuffled string has score equal to number of characters $Length = $String.Length $Score = $Length   # While still striving for perfection... While ( $Score -gt $BestScore ) { # For each character ForEach ( $i in 0..($Length-1) ) { # If the shuffled character still matches the original character... If ( $S1[$i] -eq $S2[$i] ) { # Swap it with a random character # (Random character $j may be the same as or may even be # character $i. The minor impact on speed was traded for # a simple solution to guarantee randomness.) $j = Get-Random -Maximum $Length $S2[$i], $S2[$j] = $S2[$j], $S2[$i] } } # Count the number of indexes where the two arrays match $Score = ( 0..($Length-1) ).Where({ $S1[$_] -eq $S2[$_] }).Count } # Put it back into a string $Shuffle = ( [string[]]$S2 -join '' ) return $Shuffle }
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.
#VBA
VBA
The Option Compare instruction is used at module level to declare the default comparison method to use when string data is compared. The default text comparison method is Binary.