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/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Python
Python
from bisect import bisect_right   def bin_it(limits: list, data: list) -> list: "Bin data according to (ascending) limits." bins = [0] * (len(limits) + 1) # adds under/over range bins too for d in data: bins[bisect_right(limits, d)] += 1 return bins   def bin_print(limits: list, bins: list) -> list: print(f" < {limits[0]:3} := {bins[0]:3}") for lo, hi, count in zip(limits, limits[1:], bins[1:]): print(f">= {lo:3} .. < {hi:3} := {count:3}") print(f">= {limits[-1]:3}  := {bins[-1]:3}")     if __name__ == "__main__": print("RC FIRST EXAMPLE\n") limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] bins = bin_it(limits, data) bin_print(limits, bins)   print("\nRC SECOND EXAMPLE\n") limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] bins = bin_it(limits, data) bin_print(limits, bins)
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Racket
Racket
#lang racket   (define (fold-sequence seq kons #:finalise (finalise (λ x (apply values x))) . k0s) (define (recur seq . ks) (if (null? seq) (call-with-values (λ () (apply finalise ks)) (λ vs (apply values vs))) (call-with-values (λ () (apply kons (car seq) ks)) (λ ks+ (apply recur (cdr seq) ks+))))) (apply recur (if (string? seq) (string->list (regexp-replace* #px"[^ACGT]" seq "")) seq) k0s))   (define (sequence->pretty-printed-string seq) (define (fmt idx cs-rev) (format "~a: ~a" (~a idx #:width 3 #:align 'right) (list->string (reverse cs-rev)))) (fold-sequence seq (λ (b n start-idx lns-rev cs-rev) (if (zero? (modulo n 50)) (values (+ n 1) n (if (pair? cs-rev) (cons (fmt start-idx cs-rev) lns-rev) lns-rev) (cons b null)) (values (+ n 1) start-idx lns-rev (cons b cs-rev)))) 0 0 null null #:finalise (λ (n idx lns-rev cs-rev) (string-join (reverse (if (null? cs-rev) lns-rev (cons (fmt idx cs-rev) lns-rev))) "\n"))))   (define (count-bases b as cs gs ts n) (values (+ as (if (eq? b #\A) 1 0)) (+ cs (if (eq? b #\C) 1 0)) (+ gs (if (eq? b #\T) 1 0)) (+ ts (if (eq? b #\G) 1 0)) (add1 n)))   (define (bioinformatics-Base_count s) (define-values (as cs gs ts n) (fold-sequence s count-bases 0 0 0 0 0)) (printf "SEQUENCE:~%~%~a~%~%" (sequence->pretty-printed-string s)) (printf "BASE COUNT:~%-----------~%~%~a~%~%" (string-join (map (λ (c n) (format " ~a :~a" c (~a #:width 4 #:align 'right n))) '(A T C G) (list as ts cs gs)) "\n")) (newline) (printf "TOTAL: ~a~%" n))   (module+ main (define the-string #<<EOS CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT EOS ) (bioinformatics-Base_count the-string))
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
my $dna = join '', lines q:to/END/; CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT END     put pretty($dna, 80); put "\nTotal bases: ", +my $bases = $dna.comb.Bag; put $bases.sort(~*.key).join: "\n";   sub pretty ($string, $wrap = 50) { $string.comb($wrap).map( { sprintf "%8d: %s", $++ * $wrap, $_ } ).join: "\n" }
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#ALGOL_W
ALGOL W
begin  % prints an integer in binary - the number must be greater than zero  % procedure printBinaryDigits( integer value n ) ; begin if n not = 0 then begin printBinaryDigits( n div 2 ); writeon( if n rem 2 = 1 then "1" else "0" ) end end binaryDigits ;    % prints an integer in binary - the number must not be negative  % procedure printBinary( integer value n ) ; begin if n = 0 then writeon( "0" ) else printBinaryDigits( n ) end printBinary ;    % test the printBinaryDigits procedure  % for i := 5, 50, 9000 do begin write(); printBinary( i ); end   end.
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Go
Go
package raster   // Line draws line by Bresenham's algorithm. func (b *Bitmap) Line(x0, y0, x1, y1 int, p Pixel) { // implemented straight from WP pseudocode dx := x1 - x0 if dx < 0 { dx = -dx } dy := y1 - y0 if dy < 0 { dy = -dy } var sx, sy int if x0 < x1 { sx = 1 } else { sx = -1 } if y0 < y1 { sy = 1 } else { sy = -1 } err := dx - dy   for { b.SetPx(x0, y0, p) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } }   func (b *Bitmap) LineRgb(x0, y0, x1, y1 int, c Rgb) { b.Line(x0, y0, x1, y1, c.Pixel()) }
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
#ooRexx
ooRexx
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Order
Order
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Locale 1033 'change decimal point char to dot. Form 80,50 ' set console to 80 characters by 50 lines \\ Function heading() get a positive double as degrees and return the compass index (1 for North) Function heading(d) { d1=d div 11.25 if d1 mod 3= 1 then d+=5.62 :d1=d div 11.25 =d1 mod 32 +1 } Dim wind$(1 to 32) wind$(1)="North", "North by east", "North-northeast", "Northeast by north", "Northeast" wind$(6)="Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast" wind$(12)="Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South" wind$(18)="South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest" wind$(24)="West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north" wind$(31)="North-northwest", "North by west" oldvalue=-2 newvalue=2 Print " angle | box | compass point" Print "-------+-----+---------------------" For i=0 to 360 step 0.005 newvalue=heading(i) if (newvalue mod 3) =2 then i+=5.62: newvalue=heading(i) if oldvalue<>newvalue then Print format$("{0:2:-6}°| {1::-2} | {2}",i, newvalue, wind$(newvalue)) : oldvalue=newvalue : refresh Next i } CheckIt  
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.
#Factor
Factor
"a=" "b=" [ write readln string>number ] bi@ { [ bitand "a AND b: " write . ] [ bitor "a OR b: " write . ] [ bitxor "a XOR b: " write . ] [ drop bitnot "NOT a: " write . ] [ abs shift "a asl b: " write . ] [ neg shift "a asr b: " write . ] } 2cleave
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.
#Fortran
Fortran
Screenres 320, 240, 8 Dim Shared As Integer w, h Screeninfo w, h Const As Ubyte cyan = 3 Const As Ubyte red = 4   Sub rellenar(c As Integer) Line (0,0) - (w/3, h/3), red, BF End Sub   Sub establecePixel(x As Integer, y As Integer, c As Integer) Pset (x,y), cyan End Sub   rellenar(12) establecePixel(10,10, cyan) Locate 12 Print "pixel 10,10 es " & Point(10,10) Print "pixel 20,20 es " & Point(20,10)   Bsave "FreeBASIC_bitmap.bmp", 0 Sleep
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
#Haskell
Haskell
bellTri :: [[Integer]] bellTri = let f xs = (last xs, xs) in map snd (iterate (f . uncurry (scanl (+))) (1, [1]))   bell :: [Integer] bell = map head bellTri   main :: IO () main = do putStrLn "First 10 rows of Bell's Triangle:" mapM_ print (take 10 bellTri) putStrLn "\nFirst 15 Bell numbers:" mapM_ print (take 15 bell) putStrLn "\n50th Bell number:" print (bell !! 49)
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
#J
J
  bell=: ([: +/\ (,~ {:))&.>@:{:   ,. bell^:(<5) <1 +--------------+ |1 | +--------------+ |1 2 | +--------------+ |2 3 5 | +--------------+ |5 7 10 15 | +--------------+ |15 20 27 37 52| +--------------+   {.&> bell^:(<15) <1 1 1 2 5 15 52 203 877 4140 21147 115975 678570 4213597 27644437 190899322   {:>bell^:49<1x 185724268771078270438257767181908917499221852770  
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 .
#F.23
F#
open System   let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I) let fibFirstNumbers nth = fibonacci |> Seq.take nth |> Seq.map (fun n -> n.ToString().[0] |> string |> Int32.Parse)   let fibFirstNumbersFrequency nth = let firstNumbers = fibFirstNumbers nth |> Seq.toList let counts = firstNumbers |> List.countBy id |> List.sort |> List.filter (fun (k, _) -> k <> 0) let total = firstNumbers |> List.length |> float counts |> List.map (fun (_, v) -> float v/total)   let benfordLaw d = log10(1.0 + (1.0/float d)) let benfordLawFigures = [1..9] |> List.map benfordLaw   let run () = printfn "Frequency of the first digit (1 through 9) in the Fibonacci sequence:" fibFirstNumbersFrequency 1000 |> List.iter (fun f -> printf $"{f:N5} ") printfn "\nBenford's law for 1 through 9:" benfordLawFigures |> List.iter (fun f -> printf $"{f:N5} ")  
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   +½.
#EchoLisp
EchoLisp
  (lib 'bigint) ;; lerge numbers (lib 'gloops) ;; classes   (define-class Rational null ((a :initform #0) (b :initform #1))) (define-method tostring (Rational) (lambda (r) (format "%50d / %d" r.a r.b))) (define-method normalize (Rational) (lambda (r) ;; divide a and b by gcd (let ((g (gcd r.a r.b))) (set! r.a (/ r.a g)) (set! r.b (/ r.b g)) (when (< r.b 0) (set! r.a ( - r.a)) (set! r.b (- r.b))) ;; denominator > 0 r)))   (define-method initialize (Rational) (lambda (r) (normalize r))) (define-method add (Rational) (lambda (r n) ;; + Rational any number (normalize (Rational (+ (* (+ #0 n) r.b) r.a) r.b)))) (define-method add (Rational Rational) (lambda (r q) ;;; + Rational Rational (normalize (Rational (+ (* r.a q.b) (* r.b q.a)) (* r.b q.b))))) (define-method sub (Rational Rational) (lambda (r q) (normalize (Rational (- (* r.a q.b) (* r.b q.a)) (* r.b q.b))))) (define-method mul (Rational Rational) (lambda (r q) (normalize (Rational (* r.a q.a) (* r.b q.b))))) (define-method mul (Rational) (lambda (r n) (normalize (Rational (* r.a (+ #0 n)) r.b )))) (define-method div (Rational Rational) (lambda (r q) (normalize (Rational (* r.a q.b) (* r.b q.a)))))  
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.
#AutoHotkey
AutoHotkey
array := "1,2,4,6,8,9" StringSplit, A, array, `, ; creates associative array MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive MsgBox % A%x% MsgBox % x := BinarySearchI(A, A0, 4) ; Iterative MsgBox % A%x%   BinarySearch(A, value, low, high) { ; A0 contains length of array If (high < low) ; A1, A2, A3...An are array elements Return not_found mid := Floor((low + high) / 2) If (A%mid% > value) ; A%mid% is automatically global since no such locals are present Return BinarySearch(A, value, low, mid - 1) Else If (A%mid% < value) Return BinarySearch(A, value, mid + 1, high) Else Return mid }   BinarySearchI(A, lengthA, value) { low := 0 high := lengthA - 1 While (low <= high) { mid := Floor((low + high) / 2) ; round to lower integer If (A%mid% > value) high := mid - 1 Else If (A%mid% < value) low := mid + 1 Else Return mid } Return not_found }
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did not change. Example tree, eetr, (0) Test cases abracadabra seesaw elk grrrrrr up a Related tasks   Anagrams/Deranged anagrams   Permutations/Derangements Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D
D
import std.stdio, std.random, std.algorithm, std.conv, std.range, std.traits, std.typecons;   auto bestShuffle(S)(in S orig) @safe if (isSomeString!S) { static if (isNarrowString!S) immutable o = orig.dtext; else alias o = orig;   auto s = o.dup; s.randomShuffle;   foreach (immutable i, ref ci; s) { if (ci != o[i]) continue; foreach (immutable j, ref cj; s) if (ci != cj && ci != o[j] && cj != o[i]) { swap(ci, cj); break; } }   return tuple(s, s.zip(o).count!q{ a[0] == a[1] }); } unittest { assert("abracadabra".bestShuffle[1] == 0); assert("immediately".bestShuffle[1] == 0); assert("grrrrrr".bestShuffle[1] == 5); assert("seesaw".bestShuffle[1] == 0); assert("pop".bestShuffle[1] == 1); assert("up".bestShuffle[1] == 0); assert("a".bestShuffle[1] == 1); assert("".bestShuffle[1] == 0); }   void main(in string[] args) @safe { if (args.length > 1) { immutable entry = args.dropOne.join(' '); const res = entry.bestShuffle; writefln("%s : %s (%d)", entry, res[]); } }
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.
#J
J
name=: ''
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.
#Java
Java
import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays;   public class MutableByteString {   private byte[] bytes; private int length;   public MutableByteString(byte... bytes) { setInternal(bytes); }   public int length() { return length; }   public boolean isEmpty() { return length == 0; }   public byte get(int index) { return bytes[check(index)]; }   public void set(byte[] bytes) { setInternal(bytes); }   public void set(int index, byte b) { bytes[check(index)] = b; }   public void append(byte b) { if (length >= bytes.length) { int len = 2 * bytes.length; if (len < 0) len = Integer.MAX_VALUE; bytes = Arrays.copyOf(bytes, len); } bytes[length] = b; length++; }   public MutableByteString substring(int from, int to) { return new MutableByteString(Arrays.copyOfRange(bytes, from, to)); }   public void replace(byte[] from, byte[] to) { ByteArrayOutputStream copy = new ByteArrayOutputStream(); if (from.length == 0) { for (byte b : bytes) { copy.write(to, 0, to.length); copy.write(b); } copy.write(to, 0, to.length); } else { for (int i = 0; i < length; i++) { if (regionEquals(i, from)) { copy.write(to, 0, to.length); i += from.length - 1; } else { copy.write(bytes[i]); } } } set(copy.toByteArray()); }   public boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) { if (Math.max(offset, otherOffset) + len < 0) return false; if (offset + len > length || otherOffset + len > other.length()) return false; for (int i = 0; i < len; i++) { if (bytes[offset + i] != other.get(otherOffset + i)) return false; } return true; }   public String toHexString() { char[] hex = new char[2 * length]; for (int i = 0; i < length; i++) { hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F); hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F); } return new String(hex); }   public String toStringUtf8() { return new String(bytes, 0, length, StandardCharsets.UTF_8); }   private void setInternal(byte[] bytes) { this.bytes = bytes.clone(); this.length = bytes.length; }   private boolean regionEquals(int offset, byte[] other) { int len = other.length; if (offset < 0 || offset + len < 0) return false; if (offset + len > length) return false; for (int i = 0; i < len; i++) { if (bytes[offset + i] != other[i]) return false; } return true; }   private int check(int index) { if (index < 0 || index >= length) throw new IndexOutOfBoundsException(String.valueOf(index)); return index; } }
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#R
R
limits1 <- c(23, 37, 43, 53, 67, 83) data1 <- c(95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55) limits2 <- c(14, 18, 249, 312, 389, 392, 513, 591, 634, 720) data2 <- c(445,814,519,697,700,130,255,889,481,122,932,77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775,47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238,62,678,98,534,622,907,406,714,184,391,913,42,560,247, 346,860,56,138,546,38,985,948,58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426,9,457,628,410,723,354,895,881,953,677,137,397,97, 854,740,83,216,421,94,517,479,292,963,376,981,480,39,257,272,157,5,316,395, 787,942,456,242,759,898,576,67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585,40,54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466,23,707,467,33,670,921,180,991,396,160,436,717,918,8,374,101,684,727,749)   createBin <- function(limits, data) sapply(0:length(limits), function(x) sum(findInterval(data, limits) == x))   #Contains some unicode magic so that we can get the infinity symbol and <= to print nicely. #Half of the battle here is making sure that we're not being thrown by R being 1-indexed. #The other half is avoiding the mathematical sin of saying that anything can be >=infinity. printBin <- function(limits, bin) { invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:", if(x == 0) "-\U221E < x <" else paste(limits[x], "\U2264 x <"), if(x == length(limits)) "\U221E" else limits[x + 1], "and contains", bin[x + 1], "elements.\n"))) }   #Showing off a one-line solution. Admittedly, calling the massive anonymous function "one-line" is generous. oneLine <- function(limits, data) { invisible(sapply(0:length(limits), function(x) cat("Bin", x, "covers the range:", if(x == 0) "-\U221E < x <" else paste(limits[x], "\U2264 x <"), if(x == length(limits)) "\U221E" else limits[x + 1], "and contains", sum(findInterval(data, limits) == x), "elements.\n"))) }   createBin(limits1, data1) printBin(limits1, createBin(limits1, data1)) createBin(limits2, data2) printBin(limits2, createBin(limits2, data2)) oneLine(limits2, c(data1, data2))#Not needed.
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX program finds the number of each base in a DNA string (along with a total). */ parse arg dna . if dna=='' | dna=="," then dna= 'cgtaaaaaattacaacgtcctttggctatctcttaaactcctgctaaatg' , 'ctcgtgctttccaattatgtaagcgttccgagacggggtggtcgattctg' , 'aggacaaaggtcaagatggagcgcatcgaacgcaataaggatcatttgat' , 'gggacgtttcgtcgacaaagtcttgtttcgagagtaacggctaccgtctt' , 'cgattctgcttataacactatgttcttatgaaatggatgttctgagttgg' , 'tcagtcccaatgtgcggggtttcttttagtacgtcgggagtggtattata' , 'tttaatttttctatatagcgatctgtatttaagcaattcatttaggttat' , 'cgccgcgatgctcggttcggaccgccaagcatctggctccactgctagtg' , 'tcctaaatttgaatggcaaacacaaataagatttagcaattcgtgtagac' , 'gaccggggacttgcatgatgggagcagctttgttaaactacgaacgtaat' dna= space(dna, 0); upper dna /*elide blanks from DNA; uppercase it. */ say '────────length of the DNA string: ' length(dna) @.= 0 /*initialize the count for all bases. */ w= 1 /*the maximum width of a base count. */ $= /*a placeholder for the names of bases.*/ do j=1 for length(dna) /*traipse through the DNA string. */ _= substr(dna, j, 1) /*obtain a base name from the DNA str. */ if pos(_, $)==0 then $= $ || _ /*if not found before, add it to list. */ @._= @._ + 1 /*bump the count of this base. */ w= max(w, length(@._) ) /*compute the maximum width number. */ end /*j*/ say do k=0 for 255; z= d2c(k) /*traipse through all possibilities. */ if pos(z, $)==0 then iterate /*Was this base found? No, then skip. */ say ' base ' z " has a basecount of: " right(@.z, w) @.tot= @.tot + @.z /*add to a grand total to verify count.*/ end /*k*/ /*stick a fork in it, we're all done. */ say say '────────total for all basecounts:' right(@.tot, w+1)
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ring
Ring
  dna = "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   dnaBase = [:A=0, :C=0, :G=0, :T=0] lenDna = len(dna) for n = 1 to lenDna dnaStr = substr(dna,n,1) switch dnaStr on "A" strA = dnaBase["A"] strA++ dnaBase["A"] = strA on "C" strC = dnaBase["C"] strC++ dnaBase["C"] = strC on "G" strG = dnaBase["G"] strG++ dnaBase["G"] = strG on "T" strT = dnaBase["T"] strT++ dnaBase["T"] = strT off next ? "A : " + dnaBase["A"] ? "T : " + dnaBase["T"] ? "C : " + dnaBase["C"] ? "G : " + dnaBase["G"]  
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.
#AppleScript
AppleScript
---------------------- BINARY STRING -----------------------   -- showBin :: Int -> String on showBin(n) script binaryChar on |λ|(n) text item (n + 1) of "01" end |λ| end script showIntAtBase(2, binaryChar, n, "") end showBin     --------------------------- TEST --------------------------- on run script on |λ|(n) intercalate(" -> ", {n as string, showBin(n)}) end |λ| end script   return unlines(map(result, {5, 50, 9000})) end run     -------------------- GENERIC FUNCTIONS ---------------------   -- showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String on showIntAtBase(base, toChr, n, rs) script showIt on |λ|(nd_, r) set {n, d} to nd_ set r_ to toChr's |λ|(d) & r if n > 0 then |λ|(quotRem(n, base), r_) else r_ end if end |λ| end script   if base ≤ 1 then "error: showIntAtBase applied to unsupported base: " & base as string else if n < 0 then "error: showIntAtBase applied to negative number: " & base as string else showIt's |λ|(quotRem(n, base), rs) end if end showIntAtBase     -- quotRem :: Integral a => a -> a -> (a, a) on quotRem(m, n) {m div n, m mod n} end quotRem     -------------------- GENERICS FOR TEST ---------------------   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- unlines :: [String] -> String on unlines(xs) intercalate(linefeed, xs) end unlines
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.
#Haskell
Haskell
module Bitmap.Line(line) where   import Bitmap import Control.Monad import Control.Monad.ST import qualified Data.STRef   var = Data.STRef.newSTRef get = Data.STRef.readSTRef mutate = Data.STRef.modifySTRef   line :: Color c => Image s c -> Pixel -> Pixel -> c -> ST s () line i (Pixel (xa, ya)) (Pixel (xb, yb)) c = do yV <- var y1 errorV <- var $ deltax `div` 2 forM_ [x1 .. x2] (\x -> do y <- get yV setPix i (Pixel $ if steep then (y, x) else (x, y)) c mutate errorV $ subtract deltay error <- get errorV when (error < 0) (do mutate yV (+ ystep) mutate errorV (+ deltax))) where steep = abs (yb - ya) > abs (xb - xa) (xa', ya', xb', yb') = if steep then (ya, xa, yb, xb) else (xa, ya, xb, yb) (x1, y1, x2, y2) = if xa' > xb' then (xb', yb', xa', ya') else (xa', ya', xb', yb') deltax = x2 - x1 deltay = abs $ y2 - y1 ystep = if y1 < y2 then 1 else -1
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oz
Oz
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PARI.2FGP
PARI/GP
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Map[List[Part[#,1], dirs[[Part[#,1]]], ToString@Part[#,2]<>"°"]&, Map[{Floor[Mod[ #+5.625 , 360]/11.25]+1,#}&,input] ]//TableForm
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.
#FALSE
FALSE
10 3 \$@$@$@$@\ { 3 copies } "a & b = "&." a | b = "|." ~a = "%~." "
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.
#FreeBASIC
FreeBASIC
Screenres 320, 240, 8 Dim Shared As Integer w, h Screeninfo w, h Const As Ubyte cyan = 3 Const As Ubyte red = 4   Sub rellenar(c As Integer) Line (0,0) - (w/3, h/3), red, BF End Sub   Sub establecePixel(x As Integer, y As Integer, c As Integer) Pset (x,y), cyan End Sub   rellenar(12) establecePixel(10,10, cyan) Locate 12 Print "pixel 10,10 es " & Point(10,10) Print "pixel 20,20 es " & Point(20,10)   Bsave "FreeBASIC_bitmap.bmp", 0 Sleep
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
#Java
Java
import java.util.ArrayList; import java.util.List;   public class Bell { private static class BellTriangle { private List<Integer> arr;   BellTriangle(int n) { int length = n * (n + 1) / 2; arr = new ArrayList<>(length); for (int i = 0; i < length; ++i) { arr.add(0); }   set(1, 0, 1); for (int i = 2; i <= n; ++i) { set(i, 0, get(i - 1, i - 2)); for (int j = 1; j < i; ++j) { int value = get(i, j - 1) + get(i - 1, j - 1); set(i, j, value); } } }   private int index(int row, int col) { if (row > 0 && col >= 0 && col < row) { return row * (row - 1) / 2 + col; } else { throw new IllegalArgumentException(); } }   public int get(int row, int col) { int i = index(row, col); return arr.get(i); }   public void set(int row, int col, int value) { int i = index(row, col); arr.set(i, value); } }   public static void main(String[] args) { final int rows = 15; BellTriangle bt = new BellTriangle(rows);   System.out.println("First fifteen Bell numbers:"); for (int i = 0; i < rows; ++i) { System.out.printf("%2d: %d\n", i + 1, bt.get(i + 1, 0)); }   for (int i = 1; i <= 10; ++i) { System.out.print(bt.get(i, 0)); for (int j = 1; j < i; ++j) { System.out.printf(", %d", bt.get(i, j)); } System.out.println(); } } }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Factor
Factor
USING: assocs compiler.tree.propagation.call-effect formatting kernel math math.functions math.statistics math.text.utils sequences ; IN: rosetta-code.benfords-law   : expected ( n -- x ) recip 1 + log10 ;   : next-fib ( vec -- vec' ) [ last2 ] keep [ + ] dip [ push ] keep ;   : data ( -- seq ) V{ 1 1 } clone 998 [ next-fib ] times ;   : 1st-digit ( n -- m ) 1 digit-groups last ;   : leading ( -- seq ) data [ 1st-digit ] map ;   : .header ( -- ) "Digit" "Expected" "Actual" "%-10s%-10s%-10s\n" printf ;   : digit-report ( digit digit-count -- digit expected actual ) dupd [ expected ] dip 1000 /f ;   : .digit-report ( digit digit-count -- ) digit-report "%-10d%-10.4f%-10.4f\n" printf ;   : main ( -- ) .header leading histogram [ .digit-report ] assoc-each ;   MAIN: main
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Forth
Forth
: 3drop drop 2drop ; : f2drop fdrop fdrop ;   : int-array create cells allot does> swap cells + ;   : 1st-fib 0e 1e ; : next-fib ftuck f+ ;   : 1st-digit ( fp -- n ) pad 6 represent 3drop pad c@ [char] 0 - ;   10 int-array counts   : tally 0 counts 10 cells erase 1st-fib 1000 0 DO 1 fdup 1st-digit counts +! next-fib LOOP f2drop ;   : benford ( d -- fp ) s>f 1/f 1e f+ flog ;   : tab 9 emit ;   : heading ( -- ) cr ." Leading digital distribution of the first 1,000 Fibonacci numbers:" cr ." Digit" tab ." Actual" tab ." Expected" ;   : .fixed ( n -- ) \ print count as decimal fraction s>d <# # # # [char] . hold #s #> type space ;   : report ( -- ) precision 3 set-precision heading 10 1 DO cr i 3 .r tab i counts @ .fixed tab i benford f. LOOP set-precision ;   : compute-benford tally report ;
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   +½.
#Elixir
Elixir
defmodule Bernoulli do defmodule Rational do import Kernel, except: [div: 2]   defstruct numerator: 0, denominator: 1   def new(numerator, denominator\\1) do sign = if numerator * denominator < 0, do: -1, else: 1 {numerator, denominator} = {abs(numerator), abs(denominator)} gcd = gcd(numerator, denominator)  %Rational{numerator: sign * Kernel.div(numerator, gcd), denominator: Kernel.div(denominator, gcd)} end   def sub(a, b) do new(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator) end   def mul(a, b) when is_integer(a) do new(a * b.numerator, b.denominator) end   defp gcd(a,0), do: a defp gcd(a,b), do: gcd(b, rem(a,b)) end   def numbers(n) do Stream.transform(0..n, {}, fn m,acc -> acc = Tuple.append(acc, Rational.new(1,m+1)) if m>0 do new = Enum.reduce(m..1, acc, fn j,ar -> put_elem(ar, j-1, Rational.mul(j, Rational.sub(elem(ar,j-1), elem(ar,j)))) end) {[elem(new,0)], new} else {[elem(acc,0)], acc} end end) |> Enum.to_list end   def task(n \\ 61) do b_nums = numbers(n) width = Enum.map(b_nums, fn b -> b.numerator |> to_string |> String.length end) |> Enum.max format = 'B(~2w) = ~#{width}w / ~w~n' Enum.with_index(b_nums) |> Enum.each(fn {b,i} -> if b.numerator != 0, do: :io.fwrite format, [i, b.numerator, b.denominator] end) end end   Bernoulli.task
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#F.23
F#
  open MathNet.Numerics open System open System.Collections.Generic   let calculateBernoulli n = let ℚ(x) = BigRational.FromInt x let A = Array.init<BigRational> (n+1) (fun x -> ℚ(x+1))   for m in [1..n] do A.[m] <- ℚ(1) / (ℚ(m) + ℚ(1)) for j in [m..(-1)..1] do A.[j-1] <- ℚ(j) * (A.[j-1] - A.[j]) A.[0]   [<EntryPoint>] let main argv = for n in [0..60] do let bernoulliNumber = calculateBernoulli n match bernoulliNumber.Numerator.IsZero with | false -> let formatedString = String.Format("B({0, 2}) = {1, 44} / {2}", n, bernoulliNumber.Numerator, bernoulliNumber.Denominator) printfn "%s" formatedString | true -> printf "" 0  
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number. As the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number. Task Given the starting point of a range, the ending point of a range, and the "secret value", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also. There are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them. All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially). Any of the examples can be converted into an equivalent example using "exclusive" upper bound (i.e. high = N initially) by making the following simple changes (which simply increase high by 1): change high = N-1 to high = N change high = mid-1 to high = mid (for recursive algorithm) change if (high < low) to if (high <= low) (for iterative algorithm) change while (low <= high) to while (low < high) Traditional algorithm The algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the "insertion point" for it (the index that the value would have if it were inserted into the array). Recursive Pseudocode: // initially called with low = 0, high = N-1 BinarySearch(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high if (high < low) return not_found // value would be inserted at index "low" mid = (low + high) / 2 if (A[mid] > value) return BinarySearch(A, value, low, mid-1) else if (A[mid] < value) return BinarySearch(A, value, mid+1, high) else return mid } Iterative Pseudocode: BinarySearch(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else if (A[mid] < value) low = mid + 1 else return mid } return not_found // value would be inserted at index "low" } Leftmost insertion point The following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Left(A[0..N-1], value, low, high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] >= value) return BinarySearch_Left(A, value, low, mid-1) else return BinarySearch_Left(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Left(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value > A[i] for all i < low value <= A[i] for all i > high mid = (low + high) / 2 if (A[mid] >= value) high = mid - 1 else low = mid + 1 } return low } Rightmost insertion point The following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values. Recursive Pseudocode: // initially called with low = 0, high = N - 1 BinarySearch_Right(A[0..N-1], value, low, high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high if (high < low) return low mid = (low + high) / 2 if (A[mid] > value) return BinarySearch_Right(A, value, low, mid-1) else return BinarySearch_Right(A, value, mid+1, high) } Iterative Pseudocode: BinarySearch_Right(A[0..N-1], value) { low = 0 high = N - 1 while (low <= high) { // invariants: value >= A[i] for all i < low value < A[i] for all i > high mid = (low + high) / 2 if (A[mid] > value) high = mid - 1 else low = mid + 1 } return low } Extra credit Make sure it does not have overflow bugs. The line in the pseudo-code above to calculate the mean of two integers: mid = (low + high) / 2 could produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and low + high overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result. One way to fix it is to manually add half the range to the low number: mid = low + (high - low) / 2 Even though this is mathematically equivalent to the above, it is not susceptible to overflow. Another way for signed integers, possibly faster, is the following: mid = (low + high) >>> 1 where >>> is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift. Related task Guess the number/With Feedback (Player) See also wp:Binary search algorithm Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken.
#AWK
AWK
function binary_search(array, value, left, right, middle) { if (right < left) return 0 middle = int((right + left) / 2) if (value == array[middle]) return 1 if (value < array[middle]) return binary_search(array, value, left, middle - 1) return binary_search(array, value, middle + 1, right) }
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
#Delphi
Delphi
  program Best_shuffle;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   type TShuffledString = record private original: string; Shuffled: TStringBuilder; ignoredChars: Integer; procedure DetectIgnores; procedure Shuffle; procedure Swap(pos1, pos2: Integer); function TrySwap(pos1, pos2: Integer): Boolean; function GetShuffled: string; public class operator Implicit(convert: string): TShuffledString; constructor Create(Word: string); procedure Free; property Ignored: integer read ignoredChars; property ToString: string read GetShuffled; end;   { TShuffledString }   procedure TShuffledString.Swap(pos1, pos2: Integer); var temp: char; begin temp := shuffled[pos1]; shuffled[pos1] := shuffled[pos2]; shuffled[pos2] := temp; end;   function TShuffledString.TrySwap(pos1, pos2: Integer): Boolean; begin if (original[pos1] = shuffled[pos2]) or (original[pos2] = shuffled[pos1]) then Exit(false) else Exit(true); end;   procedure TShuffledString.Shuffle; var length, swaps: Integer; used: TList<Integer>; i, j, k: Integer; begin Randomize;   length := original.Length; used := TList<Integer>.create();   for i := 0 to length - 1 do begin swaps := 0; while used.Count <= (length - i) do begin j := i + Random(length - 1 - i);   if (original[i] <> original[j]) and TrySwap(i, j) and (not used.Contains(j)) then begin Swap(i, j); Inc(swaps); break; end else used.Add(j); end;   if swaps = 0 then begin for k := i downto 0 do begin if TrySwap(i, k) then Swap(i, k); end; end; used.Clear(); end; used.Free; end;   constructor TShuffledString.Create(Word: string); begin original := Word; shuffled := TStringBuilder.create(Word); Shuffle(); DetectIgnores(); end;   procedure TShuffledString.DetectIgnores; var ignores, i: Integer; begin ignores := 0; for i := 0 to original.Length - 1 do begin if original[i] = shuffled[i] then Inc(ignores); end; ignoredChars := ignores; end;   procedure TShuffledString.Free; begin Shuffled.Free; end;   function TShuffledString.GetShuffled: string; begin result := shuffled.ToString(); end;   class operator TShuffledString.Implicit(convert: string): TShuffledString; begin result := TShuffledString.Create(convert); end;   var words: array of string; Word: TShuffledString; w: string;   begin words := ['abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a']; for w in words do begin Word := w; writeln(format('%s, %s, (%d)', [Word.Original, Word.ToString, Word.Ignored])); Word.Free; end; Readln; 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.
#JavaScript
JavaScript
//String creation var str=''; //or str2=new String();     //String assignment str="Hello"; //or str2=', Hey there'; //can use " or ' str=str+str2;//concantenates //string deletion delete str2;//this will return true or false, true when it has been successfully deleted, it shouldn't/won't work when the variable has been declared with the keyword 'var', you don't have to initialize variables with the var keyword in JavaScript, but when you do, you cannot 'delete' them. However JavaScript garbage collects, so when the function returns, the variable declared on the function is erased.   //String comparison str!=="Hello"; //!== not equal-> returns true there's also !=== str=="Hello, Hey there"; //returns true //compares 'byte' by 'byte' "Character Z">"Character A"; //returns true, when using > or < operators it converts the string to an array and evalues the first index that is higher than another. (using unicode values) in this case 'Z' char code is 90 (decimal) and 'A' char code is 65, therefore making one string "larger" than the other.   //String cloning and copying string=str;//Strings are immutable therefore when you assign a string to a variable another one is created. So for two variables to have the 'same' string you have to add that string to an object, and get/set the string from that object   //Check if a string is empty Boolean(''); //returns false ''[0]; //returns undefined ''.charCodeAt(); //returns NaN ''==0; //returns true ''===0; //returns false ''==false; //returns true   //Append byte to String str+="\x40";//using + operator before the equal sign on a string makes it equal to str=str+"\x40"   //Extract a substring from a string //str is "Hello, Hey there@" str.substr(3); //returns "lo, Hey there@" str.substr(-5); //returns "here@" negative values just go to the end str.substr(7,9); //returns "Hey there" index of 7 + 9 characters after the 7 str.substring(3); //same as substr str.substring(-5); //negative values don't work on substring same as substr(0) str.substring(7,9); //returns "He" that is, whatever is between index 7 and index 9, same as substring(9,7)   //Replace every occurence of x byte with another string str3="url,url,url,url,url"; str3.replace(/,/g,'\n') //Regex ,returns the same string with the , replaced by \n str4=str3.replace(/./g,function(index){//it also supports callback functions, the function will be called when a match has been found.. return index==','?'\n':index;//returns replacement })   //Join Strings [str," ",str3].join(" "/*this is the character that will glue the strings*/)//we can join an array of strings str3+str4; str.concat('\n',str4); //concantenate them
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Racket
Racket
#lang racket   (define (find-bin-index limits v) (let inner ((l 0) (r (vector-length limits))) (let ((m (quotient (+ l r) 2))) (if (< v (vector-ref limits m)) (if (= m l) l (inner l m)) (if (= m (sub1 r)) r (inner m r))))))   (define ((bin-given-limits! limits) data (bins (make-vector (add1 (vector-length limits)) 0))) (for ((d data)) (let ((i (find-bin-index limits d))) (vector-set! bins i (add1 (vector-ref bins i))))) bins)   (define (report-bins-given-limits limits data) (for ((b ((bin-given-limits! limits) data)) (ge (in-sequences (in-value -Inf.0) limits)) (lt (in-sequences limits (in-value +Inf.0)))) (printf "~a <= v < ~a : ~a~%" ge lt b)))   (define (Bin-given-limits) (report-bins-given-limits #[23 37 43 53 67 83] (list 95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55)) (newline) (report-bins-given-limits #[14 18 249 312 389 392 513 591 634 720] (list 445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933 416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306 655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247 346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123 345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97 854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395 787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692 698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237 605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791 466 23 707 467 33 670 921 180 991 396 160 436 717 918 8 374 101 684 727 749)))   (module+ main (Bin-given-limits))
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Raku
Raku
  sub bin_it ( @limits, @data ) { my @ranges = ( -Inf, |@limits, Inf ).rotor( 2 => -1 ).map: { .[0] ..^ .[1] }; my @binned = @data.classify(-> $d { @ranges.grep(-> $r { $d ~~ $r }) }); my %counts = @binned.map: { .key => .value.elems }; return @ranges.map: { $_ => ( %counts{$_} // 0 ) }; } sub bin_format ( @bins ) { return @bins.map: { .key.gist.fmt('%9s => ') ~ .value.fmt('%2d') }; }   my @tests = { limits => (23, 37, 43, 53, 67, 83), data => (95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55), }, { limits => (14, 18, 249, 312, 389, 392, 513, 591, 634, 720), data => ( 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749 ), }, ; for @tests -> ( :@limits, :@data ) { my @bins = bin_it( @limits, @data ); .say for bin_format(@bins); say ''; }  
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Ruby
Ruby
dna = <<DNA_STR CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT DNA_STR   chunk_size = 60 dna = dna.delete("\n") size = dna.size   0.step(size, chunk_size) do |pos| puts "#{pos.to_s.ljust(6)} #{dna[pos, chunk_size]}" end   puts dna.chars.tally.sort.map{|ar| ar.join(" : ") } puts "Total : #{dna.size}"  
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Rust
Rust
  use std::collections::HashMap;   fn main() { let dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";   let mut base_count = HashMap::new(); let mut total_count = 0; print!("Sequence:"); for base in dna.chars() { if total_count % 50 == 0 { print!("\n{:3}: ", total_count); } print!("{}", base); total_count += 1; let count = base_count.entry(base).or_insert(0); // Return current count for base or insert 0 *count += 1; } println!("\n"); println!("Base count:"); println!("-----------");   let mut base_count: Vec<_> = base_count.iter().collect(); // HashMaps can't be sorted, so collect into Vec base_count.sort_by_key(|bc| bc.0); // Sort bases alphabetically for (base, count) in base_count.iter() { println!(" {}: {:3}", base, count); } println!(); println!("Total: {}", total_count); }  
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.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program binarydigit.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data   sMessAffBin: .ascii "The decimal value " sZoneDec: .space 12,' ' .ascii " should produce an output of " sZoneBin: .space 36,' ' .asciz "\n"   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* save des 2 registres */ mov r0,#5 ldr r1,iAdrsZoneDec bl conversion10S @ decimal conversion bl conversion2 @ binary conversion and display résult mov r0,#50 ldr r1,iAdrsZoneDec bl conversion10S bl conversion2 mov r0,#-1 ldr r1,iAdrsZoneDec bl conversion10S bl conversion2 mov r0,#1 ldr r1,iAdrsZoneDec bl conversion10S bl conversion2   100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrsZoneDec: .int sZoneDec /******************************************************************/ /* register conversion in binary */ /******************************************************************/ /* r0 contains the register */ conversion2: push {r0,lr} /* save registers */ push {r1-r5} /* save others registers */ ldr r1,iAdrsZoneBin @ address reception area clz r2,r0 @ number of left zeros bits rsb r2,#32 @ number of significant bits mov r4,#' ' @ space add r3,r2,#1 @ position counter in reception area 1: strb r4,[r1,r3] @ space in other location of reception area add r3,#1 cmp r3,#32 @ end of area ? ble 1b @ no! loop mov r3,r2 @ position counter of the written character 2: @ loop lsrs r0,#1 @ shift right one bit with flags movcc r4,#48 @ carry clear => character 0 movcs r4,#49 @ carry set => character 1 strb r4,[r1,r3] @ character in reception area at position counter sub r3,r3,#1 @ subs r2,r2,#1 @ 0 bits ? bgt 2b @ no! loop   ldr r0,iAdrsZoneMessBin bl affichageMess   100: pop {r1-r5} /* restaur others registers */ pop {r0,lr} bx lr iAdrsZoneBin: .int sZoneBin iAdrsZoneMessBin: .int sMessAffBin   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registres */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registres */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */ /***************************************************/ /* conversion registre en décimal signé */ /***************************************************/ /* r0 contient le registre */ /* r1 contient l adresse de la zone de conversion */ conversion10S: push {fp,lr} /* save des 2 registres frame et retour */ push {r0-r5} /* save autres registres */ mov r2,r1 /* debut zone stockage */ mov r5,#'+' /* par defaut le signe est + */ cmp r0,#0 /* nombre négatif ? */ movlt r5,#'-' /* oui le signe est - */ mvnlt r0,r0 /* et inversion en valeur positive */ addlt r0,#1 mov r4,#10 /* longueur de la zone */ 1: /* debut de boucle de conversion */ bl divisionpar10 /* division */ add r1,#48 /* ajout de 48 au reste pour conversion ascii */ strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ sub r4,r4,#1 /* position précedente */ cmp r0,#0 bne 1b /* boucle si quotient different de zéro */ strb r5,[r2,r4] /* stockage du signe à la position courante */ subs r4,r4,#1 /* position précedente */ blt 100f /* si r4 < 0 fin */ /* sinon il faut completer le debut de la zone avec des blancs */ mov r3,#' ' /* caractere espace */ 2: strb r3,[r2,r4] /* stockage du byte */ subs r4,r4,#1 /* position précedente */ bge 2b /* boucle si r4 plus grand ou egal a zero */ 100: /* fin standard de la fonction */ pop {r0-r5} /*restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres frame et retour */ bx lr   /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 contient le dividende */ /* r0 retourne le quotient */ /* r1 retourne le reste */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save others registers */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667    
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.
#J
J
thru=: <./ + -~ i.@+ _1 ^ > NB. integers from x through y   NB.*getBresenhamLine v Returns points for a line given start and end points NB. y is: y0 x0 ,: y1 x1 getBresenhamLine=: monad define steep=. ([: </ |@-~/) y points=. |."1^:steep y slope=. %~/ -~/ points ypts=. thru/ {."1 points xpts=. ({: + 0.5 <.@:+ slope * ypts - {.) {.points |."1^:steep ypts,.xpts )   NB.*drawLines v Draws lines (x) on image (y) NB. x is: 2-item list (start and end points) ; (color) drawLines=: (1&{:: ;~ [: ; [: <@getBresenhamLine"2 (0&{::))@[ setPixels ]
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
#Pascal
Pascal
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Perl
Perl
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#MATLAB_.2F_Octave
MATLAB / Octave
function b = compassbox(d) b = ceil(mod(d+360/64,360)*32/360); end;
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#Forth
Forth
: arshift 0 ?do 2/ loop ; \ 2/ is an arithmetic shift right by one bit (2* shifts left one bit) : bitwise ( a b -- ) cr ." a = " over . ." b = " dup . cr ." a and b = " 2dup and . cr ." a or b = " 2dup or . cr ." a xor b = " 2dup xor . cr ." not a = " over invert . cr ." a shl b = " 2dup lshift . cr ." a shr b = " 2dup rshift . cr ." a ashr b = " 2dup arshift . 2drop ;
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.
#Go
Go
package main   import ( "bytes" "fmt" "image" "image/color" "image/draw" "image/png" )   func main() { // A rectangle from 0,0 to 300,240. r := image.Rect(0, 0, 300, 240)   // Create an image im := image.NewNRGBA(r)   // set some color variables for convience var ( red = color.RGBA{0xff, 0x00, 0x00, 0xff} blue = color.RGBA{0x00, 0x00, 0xff, 0xff} )   // Fill with a uniform color draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src)   // Set individual pixels im.Set(10, 20, blue) im.Set(20, 30, color.Black) im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff})   // Get the values of specific pixels as color.Color types. // The color will be in the color.Model of the image (in this // case color.NRGBA) but color models can convert their values // to other models. c1 := im.At(0, 0) c2 := im.At(10, 20)   // or directly as RGB components (scaled values) redc, greenc, bluec, _ := c1.RGBA() redc, greenc, bluec, _ = im.At(30, 40).RGBA()   // Images can be read and writen in various formats var buf bytes.Buffer err := png.Encode(&buf, im) if err != nil { fmt.Println(err) }   fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) fmt.Println(buf.Len(), "bytes when encoded as PNG.") fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", image.Pt(30, 40), redc, greenc, bluec) }
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
#jq
jq
# nth Bell number def bell: . as $n | if $n < 0 then "non-negative integer expected" elif $n < 2 then 1 else reduce range(1; $n) as $i ([1]; reduce range(1; $i) as $j (.; .[$i - $j] as $x | .[$i - $j - 1] += $x ) | .[$i] = .[0] + .[$i - 1] ) | .[$n - 1] end;   # The task range(1;51) | 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
#Julia
Julia
""" bellnum(n) Compute the ``n``th Bell number. """ function bellnum(n::Integer) if n < 0 throw(DomainError(n)) elseif n < 2 return 1 end list = Vector{BigInt}(undef, n) list[1] = 1 for i = 2:n for j = 1:i - 2 list[i - j - 1] += list[i - j] end list[i] = list[1] + list[i - 1] end return list[n] end   for i in 1:50 println(bellnum(i)) 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 .
#Fortran
Fortran
-*- mode: compilation; default-directory: "/tmp/" -*- Compilation started at Sat May 18 01:13:00   a=./f && make $a && $a f95 -Wall -ffree-form f.F -o f 0.301030010 0.176091254 0.124938756 9.69100147E-02 7.91812614E-02 6.69467747E-02 5.79919666E-02 5.11525236E-02 4.57575098E-02 THE LAW 0.300999999 0.177000001 0.125000000 9.60000008E-02 7.99999982E-02 6.70000017E-02 5.70000000E-02 5.29999994E-02 4.50000018E-02 LEADING FIBONACCI DIGIT   Compilation finished at Sat May 18 01:13:00
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 .
#FreeBASIC
FreeBASIC
' version 27-10-2016 ' compile with: fbc -s console   #Define max 1000 ' total number of Fibonacci numbers #Define max_sieve 15485863 ' should give 1,000,000   #Include Once "gmp.bi" ' uses the GMP libary   Dim As ZString Ptr z_str Dim As ULong n, d ReDim As ULong digit(1 To 9) Dim As Double expect, found   Dim As mpz_ptr fib1, fib2 fib1 = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(fib1, 0) fib2 = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(fib2, 1)   digit(1) = 1 ' fib2 For n = 2 To max Swap fib1, fib2 ' fib1 = 1, fib2 = 0 mpz_add(fib2, fib1, fib2) ' fib1 = 1, fib2 = 1 (fib1 + fib2) z_str = mpz_get_str(0, 10, fib2) d = Val(Left(*z_str, 1)) ' strip the 1 digit on the left off digit(d) = digit(d) +1 Next   mpz_clear(fib1) : DeAllocate(fib1) mpz_clear(fib2) : DeAllocate(fib2)   Print Print "First 1000 Fibonacci numbers" Print "nr: total found expected difference"   For d = 1 To 9 n = digit(d) found = n / 10 expect = (Log(1 + 1 / d) / Log(10)) * 100 Print Using " ## ##### ###.## % ###.## % ##.### %"; _ d; n ; found; expect; expect - found Next     ReDim digit(1 To 9) ReDim As UByte sieve(max_sieve)   'For d = 4 To max_sieve Step 2 ' sieve(d) = 1 'Next Print : Print "start sieve" For d = 3 To sqr(max_sieve) If sieve(d) = 0 Then For n = d * d To max_sieve Step d * 2 sieve(n) = 1 Next End If Next   digit(2) = 1 ' 2   Print "start collecting first digits" For n = 3 To max_sieve Step 2 If sieve(n) = 0 Then d = Val(Left(Trim(Str(n)), 1)) digit(d) = digit(d) +1 End If Next   Dim As ulong total For n = 1 To 9 total = total + digit(n) Next   Print Print "First";total; " primes" Print "nr: total found expected difference"   For d = 1 To 9 n = digit(d) found = n / total * 100 expect = (Log(1 + 1 / d) / Log(10)) * 100 Print Using " ## ######## ###.## % ###.## % ###.### %"; _ d; n ; found; expect; expect - found Next     ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep 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   +½.
#Factor
Factor
IN: scratchpad [ 0 1 1 "%2d : %d / %d\n" printf 1 -1 2 "%2d : %d / %d\n" printf 30 iota [ 1 + 2 * dup bernoulli [ numerator ] [ denominator ] bi "%2d : %d / %d\n" printf ] each ] time 0 : 1 / 1 1 : -1 / 2 2 : 1 / 6 4 : -1 / 30 6 : 1 / 42 8 : -1 / 30 10 : 5 / 66 12 : -691 / 2730 14 : 7 / 6 16 : -3617 / 510 18 : 43867 / 798 20 : -174611 / 330 22 : 854513 / 138 24 : -236364091 / 2730 26 : 8553103 / 6 28 : -23749461029 / 870 30 : 8615841276005 / 14322 32 : -7709321041217 / 510 34 : 2577687858367 / 6 36 : -26315271553053477373 / 1919190 38 : 2929993913841559 / 6 40 : -261082718496449122051 / 13530 42 : 1520097643918070802691 / 1806 44 : -27833269579301024235023 / 690 46 : 596451111593912163277961 / 282 48 : -5609403368997817686249127547 / 46410 50 : 495057205241079648212477525 / 66 52 : -801165718135489957347924991853 / 1590 54 : 29149963634884862421418123812691 / 798 56 : -2479392929313226753685415739663229 / 870 58 : 84483613348880041862046775994036021 / 354 60 : -1215233140483755572040304994079820246041491 / 56786730 Running time: 0.00489444 seconds
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.
#Axe
Axe
Lbl BSEARCH 0→L r₃-1→H While L≤H (L+H)/2→M If {L+M}>r₂ M-1→H ElseIf {L+M}<r₂ M+1→L Else M Return End End -1 Return
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
#Elena
Elena
import system'routines; import extensions; import extensions'text;   extension op { get Shuffled() { var original := self.toArray(); var shuffled := self.toArray();   for (int i := 0, i < original.Length, i += 1) { for (int j := 0, j < original.Length, j += 1) { if (i != j && original[i] != shuffled[j] && original[j] != shuffled[i]) { shuffled.exchange(i,j) } } };   ^ shuffled.summarize(new StringWriter()).toString() }   score(originalText) { var shuffled := self.toArray(); var original := originalText.toArray(); int score := 0;   for (int i := 0, i < original.Length, i += 1) { if (original[i] == shuffled[i]) { score += 1 } };   ^ score } }   public program() { new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach:(s) { var shuffled_s := s.Shuffled;   console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")") };   console.readChar() }
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
#Erlang
Erlang
  -module( best_shuffle ).   -export( [sameness/2, string/1, task/0] ).   sameness( String1, String2 ) -> lists:sum( [1 || {X, X} <- lists:zip(String1, String2)] ).   string( String ) -> {"", String, Acc} = lists:foldl( fun different/2, {lists:reverse(String), String, []}, String ), lists:reverse( Acc ).   task() -> Strings = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"], Shuffleds = [string(X) || X <- Strings], [io:fwrite("~p ~p ~p~n", [X, Y, sameness(X,Y)]) || {X, Y} <- lists:zip(Strings, Shuffleds)].       different( Character, {[Character], Original, Acc} ) -> try_to_save_last( Character, Original, Acc ); different( Character, {[Character | T]=Not_useds, Original, Acc} ) -> Different_or_same = different_or_same( [X || X <- T, X =/= Character], Character ), {lists:delete(Different_or_same, Not_useds), Original, [Different_or_same | Acc]}; different( _Character1, {[Character2 | T], Original, Acc} ) -> {T, Original, [Character2 | Acc]}.   different_or_same( [Different | _T], _Character ) -> Different; different_or_same( [], Character ) -> Character.   try_to_save_last( Character, Original_string, Acc ) -> Fun = fun ({X, Y}) -> (X =:= Y) orelse (X =:= Character) end, New_acc = try_to_save_last( lists:splitwith(Fun, lists:zip(lists:reverse(Original_string), [Character | Acc])), [Character | Acc] ), {"", Original_string, New_acc}.   try_to_save_last( {_Not_split, []}, Acc ) -> Acc; try_to_save_last( {Last_reversed_zip, First_reversed_zip}, _Acc ) -> {_Last_reversed_original, [Last_character_acc | Last_part_acc]} = lists:unzip( Last_reversed_zip ), {_First_reversed_original, [Character_acc | First_part_acc]} = lists:unzip( First_reversed_zip ), [Character_acc | Last_part_acc] ++ [Last_character_acc | First_part_acc].  
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.
#jq
jq
# If the input is a valid representation of a binary string # then pass it along: def check_binary: . as $a | reduce .[] as $x ($a; if $x | (type == "number" and . == floor and 0 <= . and . <= 255) then $a else error("\(.) is an invalid representation of a byte") 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.
#Julia
Julia
  # String assignment. Creation and garbage collection are automatic. a = "123\x00 abc " # strings can contain bytes that are not printable in the local font b = "456" * '\x09' c = "789" println(a) println(b) println(c)   # string comparison println("(a == b) is $(a == b)")   # String copying. A = a B = b C = c println(A) println(B) println(C)   # check if string is empty if length(a) == 0 println("string a is empty") else println("string a is not empty") end   # append a byte (actually this is a Char in Julia, and may also be up to 32 bit Unicode) to a string a= a * '\x64' println(a)   # extract a substring from string e = a[1:6] println(e)   # repeat strings with ^ b4 = b ^ 4 println(b4)   # Replace every occurrence of a string in another string with third string r = replace(b4, "456" => "xyz") println(r)   # join strings with * d = a * b * c println(d)  
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#REXX
REXX
/*REXX program counts how many numbers of a set that fall in the range of each bin. */ lims= 23 37 43 53 67 83 /* ◄■■■■■■1st set of bin limits & data.*/ data= 95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 , 16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55 call lims lims; call bins data call show 'the 1st set of bin counts for the specified data:' say; say; say lims= 14 18 249 312 389 392 513 591 634 720 /* ◄■■■■■■2nd set of bin limits & data.*/ data= 445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933 , 416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306 , 655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247 , 346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123 , 345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97 , 854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395 , 787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692 , 698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237 , 605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791 , 466 23 707 467 33 670 921 180 991 396 160 436 717 918 8 374 101 684 727 749 call lims lims; call bins data call show 'the 2nd set of bin counts for the specified data:' exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bins: parse arg nums; !.= 0; datum= words(nums); wc= length(datum) /*max width count.*/ do j=1 for datum; x= word(nums, j) do k=0 for # /*find the bin that this number is in. */ if x < @.k then do;  !.k= !.k + 1; iterate j; end /*bump a bin count*/ end /*k*/  !.k= !.k + 1 /*number is > the highest bin specified*/ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ lims: parse arg limList; #= words(limList); wb= 0 /*max width binLim*/ do j=1 for #; _= j - 1; @._= word(limList, j); wb= max(wb, length(@._) ) end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: parse arg t; say center(t, 51 ); $= left('', 9) /*$: for indentation*/ say center('', 51, "═") /*show title separator.*/ jp= # - 1; ge= '≥'; le='<'; eq= ' count=' do j=0 for #; jm= j - 1; bin= right(@.j, wb) if j==0 then say $ left('', length(ge) +3+wb+length(..) )le bin eq right(!.j, wc) else say $ ge right(@.jm, wb) .. le bin eq right(!.j, wc) if j==jp then say $ ge right(@.jp,wb) left('', 3+length(..)+wb) eq right(!.#, wc) end /*j*/; return
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Swift
Swift
import Foundation   let dna = """ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT """   print("input:\n\(dna)\n")   let counts = dna.replacingOccurrences(of: "\n", with: "").reduce(into: [:], { $0[$1, default: 0] += 1 })   print("Counts: \(counts)") print("Total: \(counts.values.reduce(0, +))")
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Tcl
Tcl
namespace path ::tcl::mathop   proc process {data {width 50}} { set len [string length $data] set addrwidth [string length [* [/ $len $width] $width]] for {set i 0} {$i < $len} {incr i $width} { puts "[format %${addrwidth}u $i] [string range $data $i $i+[- $width 1]]" } puts "\nBase count:" foreach base {A C G T} { puts "$base [regexp -all $base $data]" } puts "Total $len" }     set test [string cat \ CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG \ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG \ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT \ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT \ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG \ TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA \ TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT \ CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG \ TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC \ GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT] process $test 50
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.
#Arturo
Arturo
print as.binary 5 print as.binary 50 print as.binary 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.
#Java
Java
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants;   public class Bresenham {   public static void main(String[] args) { SwingUtilities.invokeLater(Bresenham::run); }   private static void run() { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); f.setTitle("Bresenham");   f.getContentPane().add(new BresenhamPanel()); f.pack();   f.setLocationRelativeTo(null); f.setVisible(true); } }   class BresenhamPanel extends JPanel {   private final int pixelSize = 10;   BresenhamPanel() { setPreferredSize(new Dimension(600, 500)); setBackground(Color.WHITE); }   @Override public void paintComponent(Graphics g) { super.paintComponent(g);   int w = (getWidth() - 1) / pixelSize; int h = (getHeight() - 1) / pixelSize; int maxX = (w - 1) / 2; int maxY = (h - 1) / 2; int x1 = -maxX, x2 = maxX * -2 / 3, x3 = maxX * 2 / 3, x4 = maxX; int y1 = -maxY, y2 = maxY * -2 / 3, y3 = maxY * 2 / 3, y4 = maxY;   drawLine(g, 0, 0, x3, y1); // NNE drawLine(g, 0, 0, x4, y2); // ENE drawLine(g, 0, 0, x4, y3); // ESE drawLine(g, 0, 0, x3, y4); // SSE drawLine(g, 0, 0, x2, y4); // SSW drawLine(g, 0, 0, x1, y3); // WSW drawLine(g, 0, 0, x1, y2); // WNW drawLine(g, 0, 0, x2, y1); // NNW }   private void plot(Graphics g, int x, int y) { int w = (getWidth() - 1) / pixelSize; int h = (getHeight() - 1) / pixelSize; int maxX = (w - 1) / 2; int maxY = (h - 1) / 2;   int borderX = getWidth() - ((2 * maxX + 1) * pixelSize + 1); int borderY = getHeight() - ((2 * maxY + 1) * pixelSize + 1); int left = (x + maxX) * pixelSize + borderX / 2; int top = (y + maxY) * pixelSize + borderY / 2;   g.setColor(Color.black); g.drawOval(left, top, pixelSize, pixelSize); }   private void drawLine(Graphics g, int x1, int y1, int x2, int y2) { // delta of exact value and rounded value of the dependent variable int d = 0;   int dx = Math.abs(x2 - x1); int dy = Math.abs(y2 - y1);   int dx2 = 2 * dx; // slope scaling factors to int dy2 = 2 * dy; // avoid floating point   int ix = x1 < x2 ? 1 : -1; // increment direction int iy = y1 < y2 ? 1 : -1;   int x = x1; int y = y1;   if (dx >= dy) { while (true) { plot(g, x, y); if (x == x2) break; x += ix; d += dy2; if (d > dx) { y += iy; d -= dx2; } } } else { while (true) { plot(g, x, y); if (y == y2) break; y += iy; d += dx2; if (d > dy) { x += ix; d -= dy2; } } } } }
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
#Phix
Phix
with javascript_semantics for i=1 to 3 do integer c = (i==2), -- fine d = (c==1), -- oops e = (c==true), -- fine f = equal(c,1) -- fine, ditto equal(c,true) printf(1,"%d==2:%5t(%d) ==1:%5t, eq1:%5t, ==true:%5t\n", {i, c, c, d, e, f}) end for -- -- output on desktop/Phix: 1==2:false(0) ==1:false, eq1:false, ==true:false -- 2==2: true(1) ==1: true, eq1: true, ==true: true -- 3==2:false(0) ==1:false, eq1:false, ==true:false -- -- output on pwa/p2js: 1==2:false(0) ==1:false, eq1:false, ==true:false -- 2==2: true(1) ==1:false, eq1: true, ==true: true -- 3==2:false(0) ==1:false, eq1:false, ==true:false --
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PHP
PHP
go ?=> member(N,1..5), println(N), fail, % or false/0 to get other solutions nl. go => true.
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#Modula-2
Modula-2
MODULE BoxTheCompass; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,Write,ReadChar;   PROCEDURE expand(cp : ARRAY OF CHAR); VAR i : INTEGER = 0; BEGIN WHILE cp[i] # 0C DO IF i=0 THEN CASE cp[i] OF 'N': WriteString("North") | 'E': WriteString("East") | 'S': WriteString("South") | 'W': WriteString("West") | 'b': WriteString(" by ") ELSE WriteString("-"); END; ELSE CASE cp[i] OF 'N': WriteString("north") | 'E': WriteString("east") | 'S': WriteString("south") | 'W': WriteString("west") | 'b': WriteString(" by ") ELSE WriteString("-"); END; END; INC(i) END; END expand;   PROCEDURE FormatReal(r : REAL); VAR buf : ARRAY[0..63] OF CHAR; u,v : INTEGER; w : REAL; BEGIN u := TRUNC(r); w := r - FLOAT(u); v := TRUNC(100.0 * w);   FormatString("%6i.%'02i", buf, u, v); WriteString(buf); END FormatReal;   VAR cp : ARRAY[0..31] OF ARRAY[0..4] OF CHAR = { "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" }; buf : ARRAY[0..63] OF CHAR; i,index : INTEGER; heading : REAL; BEGIN WriteString("Index Degrees Compass point"); WriteLn; WriteString("----- ------- -------------"); WriteLn; FOR i:=0 TO 32 DO index := i MOD 32; heading := FLOAT(i) * 11.25; CASE i MOD 3 OF 1: heading := heading + 5.62; | 2: heading := heading - 5.62; ELSE (* empty *) END; FormatString("%2i ", buf, index+1); WriteString(buf); FormatReal(heading); WriteString(" "); expand(cp[index]); WriteLn END;   ReadChar END BoxTheCompass.
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.
#Fortran
Fortran
integer :: i, j = -1, k = 42 logical :: a   i = bit_size(j) ! returns the number of bits in the given INTEGER variable   ! bitwise boolean operations on integers i = iand(k, j) ! returns bitwise AND of K and J i = ior(k, j) ! returns bitwise OR of K and J i = ieor(k, j) ! returns bitwise EXCLUSIVE OR of K and J i = not(j) ! returns bitwise NOT of J   ! single-bit integer/logical operations (bit positions are zero-based) a = btest(i, 4) ! returns logical .TRUE. if bit position 4 of I is 1, .FALSE. if 0 i = ibclr(k, 8) ! returns value of K with 8th bit position "cleared" (set to 0) i = ibset(k, 13) ! returns value of K with 13th bit position "set" (set to 1)   ! multi-bit integer operations i = ishft(k, j) ! returns value of K shifted by J bit positions, with ZERO fill ! (right shift if J < 0 and left shift if J > 0). i = ishftc(k, j) ! returns value of K shifted CIRCULARLY by J bit positions ! (right circular shift if J < 0 and left if J > 0) i = ishftc(k, j, 20) ! returns value as before except that ONLY the 20 lowest order ! (rightmost) bits are circularly shifted i = ibits(k, 7, 8) ! extracts 8 contiguous bits from K starting at position 7 and ! returns them as the rightmost bits of an otherwise ! zero-filled integer. For non-negative K this is ! arithmetically equivalent to: MOD((K / 2**7), 2**8)
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.
#Haskell
Haskell
module Bitmap(module Bitmap) where   import Control.Monad import Control.Monad.ST import Data.Array.ST   newtype Pixel = Pixel (Int, Int) deriving Eq   instance Ord Pixel where compare (Pixel (x1, y1)) (Pixel (x2, y2)) = case compare y1 y2 of EQ -> compare x1 x2 v -> v   instance Ix Pixel where {- This instance differs from the one for (Int, Int) in that the ordering of indices is (0,0), (1,0), (2,0), (0,1), (1,1), (2,1) instead of (0,0), (0,1), (1,0), (1,1), (2,0), (2,1). -} range (Pixel (xa, ya), Pixel (xz, yz)) = [Pixel (x, y) | y <- [ya .. yz], x <- [xa .. xz]] index (Pixel (xa, ya), Pixel (xz, _)) (Pixel (xi, yi)) = (yi - ya)*(xz - xa + 1) + (xi - xa) inRange (Pixel (xa, ya), Pixel (xz, yz)) (Pixel (xi, yi)) = not $ xi < xa || xi > xz || yi < ya || yi > yz rangeSize (Pixel (xa, ya), Pixel (xz, yz)) = (xz - xa + 1) * (yz - ya + 1)   instance Show Pixel where show (Pixel p) = show p   class Ord c => Color c where luminance :: c -> Int -- The Int should be in the range [0 .. 255]. black, white :: c toNetpbm :: [c] -> String fromNetpbm :: [Int] -> [c] netpbmMagicNumber, netpbmMaxval :: c -> String {- The argument to these two functions is ignored; the parameter is only for typechecking. -}   newtype Color c => Image s c = Image (STArray s Pixel c)   image :: Color c => Int -> Int -> c -> ST s (Image s c) {- Creates a new image with the given width and height, filled with the given color. -} image w h = liftM Image . newArray (Pixel (0, 0), Pixel (w - 1, h - 1))   listImage :: Color c => Int -> Int -> [c] -> ST s (Image s c) {- Creates a new image with the given width and height, with each pixel set to the corresponding element of the given list. -} listImage w h = liftM Image . newListArray (Pixel (0, 0), Pixel (w - 1, h - 1))   dimensions :: Color c => Image s c -> ST s (Int, Int) dimensions (Image i) = do (_, Pixel (x, y)) <- getBounds i return (x + 1, y + 1)   getPix :: Color c => Image s c -> Pixel -> ST s c getPix (Image i) = readArray i   getPixels :: Color c => Image s c -> ST s [c] getPixels (Image i) = getElems i   setPix :: Color c => Image s c -> Pixel -> c -> ST s () setPix (Image i) = writeArray i   fill :: Color c => Image s c -> c -> ST s () fill (Image i) c = getBounds i >>= mapM_ f . range where f p = writeArray i p c   mapImage :: (Color c, Color c') => (c -> c') -> Image s c -> ST s (Image s c') mapImage f (Image i) = liftM Image $ mapArray f 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
#Kotlin
Kotlin
class BellTriangle(n: Int) { private val arr: Array<Int>   init { val length = n * (n + 1) / 2 arr = Array(length) { 0 }   set(1, 0, 1) for (i in 2..n) { set(i, 0, get(i - 1, i - 2)) for (j in 1 until i) { val value = get(i, j - 1) + get(i - 1, j - 1) set(i, j, value) } } }   private fun index(row: Int, col: Int): Int { require(row > 0) require(col >= 0) require(col < row) return row * (row - 1) / 2 + col }   operator fun get(row: Int, col: Int): Int { val i = index(row, col) return arr[i] }   private operator fun set(row: Int, col: Int, value: Int) { val i = index(row, col) arr[i] = value } }   fun main() { val rows = 15 val bt = BellTriangle(rows)   println("First fifteen Bell numbers:") for (i in 1..rows) { println("%2d: %d".format(i, bt[i, 0])) }   for (i in 1..10) { print("${bt[i, 0]}") for (j in 1 until i) { print(", ${bt[i, j]}") } println() } }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math" )   func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] }   func main() { show(Fib1000(), "First 1000 Fibonacci numbers") }   func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf("  %d  %9.3f  %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
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   +½.
#Fermat
Fermat
Func Bern(m) = Sigma<k=0,m>[Sigma<v=0,k>[(-1)^v*Bin(k,v)*(v+1)^m/(k+1)]].; for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;
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.
#BASIC
BASIC
FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer DIM middle AS Integer   IF hi < lo THEN binary_search = 0 ELSE middle = (hi + lo) / 2 SELECT CASE value CASE IS < array(middle) binary_search = binary_search(array(), value, lo, middle-1) CASE IS > array(middle) binary_search = binary_search(array(), value, middle+1, hi) CASE ELSE binary_search = middle END SELECT END IF END FUNCTION
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
#FreeBASIC
FreeBASIC
  Dim As String*11 lista(6) => {"abracadabra","seesaw","pop","grrrrrr","up","a"}   Function bestShuffle(s1 As String) As String Dim As String s2 = s1 Dim As Integer i, j, i1, j1 For i = 1 To Len(s2) For j = 1 To Len(s2) If (i <> j) And (Mid(s2,i,1) <> Mid(s1,j,1)) And (Mid(s2,j,1) <> Mid(s1,i,1)) Then If j < i Then i1 = j : j1 = i Else i1 = i : j1 = j s2 = Left(s2,i1-1) + Mid(s2,j1,1) + Mid(s2,i1+1,(j1-i1)-1) + Mid(s2,i1,1) + Mid(s2,j1+1) End If Next j Next i bestShuffle = s2 End Function   Dim As String palabra, bs Dim As Integer puntos For b As Integer = 0 To Ubound(lista)-1 palabra = lista(b) bs = bestShuffle(palabra) puntos = 0 For i As Integer = 1 To Len(palabra) If Mid(palabra,i,1) = Mid(bs,i,1) Then puntos += 1 Next i Print palabra; " ==> "; bs; " (puntuaci¢n:"; puntos; ")" Next b Sleep  
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.
#Kotlin
Kotlin
class ByteString(private val bytes: ByteArray) : Comparable<ByteString> { val length get() = bytes.size   fun isEmpty() = bytes.isEmpty()   operator fun plus(other: ByteString): ByteString = ByteString(bytes + other.bytes)   operator fun plus(byte: Byte) = ByteString(bytes + byte)   operator fun get(index: Int): Byte { require (index in 0 until length) return bytes[index] }   fun toByteArray() = bytes   fun copy() = ByteString(bytes.copyOf())   override fun compareTo(other: ByteString) = this.toString().compareTo(other.toString())   override fun equals(other: Any?): Boolean { if (other == null || other !is ByteString) return false return compareTo(other) == 0 }   override fun hashCode() = this.toString().hashCode()   fun substring(startIndex: Int) = ByteString(bytes.sliceArray(startIndex until length))   fun substring(startIndex: Int, endIndex: Int) = ByteString(bytes.sliceArray(startIndex until endIndex))   fun replace(oldByte: Byte, newByte: Byte): ByteString { val ba = ByteArray(length) { if (bytes[it] == oldByte) newByte else bytes[it] } return ByteString(ba) }   fun replace(oldValue: ByteString, newValue: ByteString) = this.toString().replace(oldValue.toString(), newValue.toString()).toByteString()   override fun toString(): String { val chars = CharArray(length) for (i in 0 until length) { chars[i] = when (bytes[i]) { in 0..127 -> bytes[i].toChar() else -> (256 + bytes[i]).toChar() } } return chars.joinToString("") } }   fun String.toByteString(): ByteString { val bytes = ByteArray(this.length) for (i in 0 until this.length) { bytes[i] = when (this[i].toInt()) { in 0..127 -> this[i].toByte() in 128..255 -> (this[i] - 256).toByte() else -> '?'.toByte() // say } } return ByteString(bytes) }   /* property to be used as an abbreviation for String.toByteString() */ val String.bs get() = this.toByteString()   fun main(args: Array<String>) { val ba = byteArrayOf(65, 66, 67) val ba2 = byteArrayOf(68, 69, 70) val bs = ByteString(ba) val bs2 = ByteString(ba2) val bs3 = bs + bs2 val bs4 = "GHI£€".toByteString() println("The length of $bs is ${bs.length}") println("$bs + $bs2 = $bs3") println("$bs + D = ${bs + 68}") println("$bs == ABC is ${bs == bs.copy()}") println("$bs != ABC is ${bs != bs.copy()}") println("$bs >= $bs2 is ${bs > bs2}") println("$bs <= $bs2 is ${bs < bs2}") println("$bs is ${if (bs.isEmpty()) "empty" else "not empty"}") println("ABC[1] = ${bs[1].toChar()}") println("ABC as a byte array is ${bs.toByteArray().contentToString()}") println("ABCDEF(1..5) = ${bs3.substring(1)}") println("ABCDEF(2..4) = ${bs3.substring(2,5)}") println("ABCDEF with C replaced by G is ${bs3.replace(67, 71)}") println("ABCDEF with CD replaced by GH is ${bs3.replace("CD".bs, "GH".bs)}") println("GHI£€ as a ByteString is $bs4") }
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Ring
Ring
  limit = [0, 23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] data = sort(data) dn = list(len(limit)) see "Example 1:" + nl + nl limits(limit,data,dn) see nl   limit = [0, 14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] data = sort(data) dn = list(len(limit)) see "Example 2:" + nl + nl limits(limit,data,dn)   func limits(limit,data,dn) for n = 1 to len(data) for m = 1 to len(limit)-1 if data[n] >= limit[m] and data[n] < limit[m+1] dn[m] += 1 ok next if data[n] >= limit[len(limit)] dn[len(limit)] += 1 ok next   for n = 1 to len(limit)-1 see ">= " + limit[n] + " and < " + limit[n+1] + " := " + dn[n] + nl next see ">= " + limit[n] + " := " + dn[n] + nl  
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Ruby
Ruby
Test = Struct.new(:limits, :data) tests = Test.new( [23, 37, 43, 53, 67, 83], [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]), Test.new( [14, 18, 249, 312, 389, 392, 513, 591, 634, 720], [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749])   def bin(limits, data) data.map{|d| limits.bsearch{|limit| limit > d} }.tally end   def present_bins(limits, bins) ranges = ([nil]+limits+[nil]).each_cons(2).map{|low, high| Range.new(low, high, true) } ranges.each{|range| puts "#{range.to_s.ljust(12)} #{bins[range.end].to_i}"} end   tests.each do |test| present_bins(test.limits, bin(test.limits, test.data)) puts end  
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vlang
Vlang
fn main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   println("SEQUENCE:") le := dna.len for i := 0; i < le; i += 50 { mut k := i + 50 if k > le { k = le } println("${i:5}: ${dna[i..k]}") } mut base_map := map[byte]int{} // allows for 'any' base for i in 0..le { base_map[dna[i]]++ } mut bases := base_map.keys() bases.sort()   println("\nBASE COUNT:") for base in bases { println(" $base: ${base_map[base]:3}") } println(" ------") println(" Σ: $le") println(" ======") }
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "/fmt" for Fmt import "/sort" for Sort import "/trait" for Stepped   var dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   System.print("SEQUENCE:") var le = dna.count for (i in Stepped.new(0...le, 50)) { var k = i + 50 if (k > le) k = le System.print("%(Fmt.d(5, i)): %(dna[i...k])") } var baseMap = {} // allows for 'any' base for (i in 0...le) { var d = dna[i] var v = baseMap[d] baseMap[d] = !v ? 1 : v + 1 } var bases = baseMap.keys.toList Sort.quick(bases)   System.print("\nBASE COUNT:") for (base in bases) { System.print("  %(base): %(Fmt.d(3, baseMap[base]))") } System.print(" ------") System.print(" Σ: %(le)") System.print(" ======")
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.
#AutoHotkey
AutoHotkey
MsgBox % NumberToBinary(5) ;101 MsgBox % NumberToBinary(50) ;110010 MsgBox % NumberToBinary(9000) ;10001100101000   NumberToBinary(InputNumber) { While, InputNumber Result := (InputNumber & 1) . Result, InputNumber >>= 1 Return, Result }
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.
#JavaScript
JavaScript
function bline(x0, y0, x1, y1) {   var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1; var dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1; var err = (dx>dy ? dx : -dy)/2;   while (true) { setPixel(x0,y0); if (x0 === x1 && y0 === y1) break; var e2 = err; if (e2 > -dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Picat
Picat
go ?=> member(N,1..5), println(N), fail, % or false/0 to get other solutions nl. go => 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
#PicoLisp
PicoLisp
  > 0; (3) Result: 0 > false; (4) Result: 0 > 0; (6) Result: 0 > !true; (7) Result: 0 > true; (8) Result: 1 > 1; (9) Result: 1 >  
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)..
#MUMPS
MUMPS
BOXING(DEGREE)  ;This takes in a degree heading, nominally from 0 to 360, and returns the compass point name. QUIT:((DEGREE<0)||(DEGREE>360)) "land lubber can't read a compass" NEW DIRS,UNP,UNPACK,SEP,DIR,DOS,D,DS,I,F SET DIRS="N^NbE^N-NE^NEbN^NE^NEbE^E-NE^EbN^E^EbS^E-SE^SEbE^SE^SEbS^S-SE^SbE^" SET DIRS=DIRS_"S^SbW^S-SW^SWbS^SW^SWbW^W-SW^WbS^W^WbN^W-NW^NWbW^NW^NWbN^N-NW^NbW" SET UNP="NESWb" SET UNPACK="north^east^south^west^ by " SET SEP=360/$LENGTH(DIRS,"^") SET DIR=(DEGREE/SEP)+1.5 SET DIR=$SELECT((DIR>33):DIR-32,1:DIR) SET DOS=$NUMBER(DIR-.5,0) SET D=$PIECE(DIRS,"^",DIR) SET DS="" FOR I=1:1:$LENGTH(D) DO . SET F=$FIND(UNP,$EXTRACT(D,I)) SET DS=DS_$SELECT((F>0):$PIECE(UNPACK,"^",F-1),1:$E(D,I)) KILL DIRS,UNP,UNPACK,SEP,DIR,D,I,F QUIT DOS_"^"_DS   BOXWRITE NEW POINTS,UP,LO,DIR,P,X SET POINTS="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," SET POINTS=POINTS_"151.88,168.75,185.62,185.63,202.5,219.37,219.38,236.25,253.12,253.13,270.0,286.87," SET POINTS=POINTS_"286.88,303.75,320.62,320.63,337.5,354.37,354.38" SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ" SET LO="abcdefghijklmnopqrstuvwxyz" FOR P=1:1:$LENGTH(POINTS,",") DO . SET X=$$BOXING($PIECE(POINTS,",",P)) . ;Capitalize the initial letter of the direction . SET DIR=$PIECE(X,"^",2) . SET DIR=$TRANSLATE($EXTRACT(DIR,1),LO,UP)_$EXTRACT(DIR,2,$LENGTH(DIR)) . WRITE $PIECE(X,"^"),?5,DIR,?40,$JUSTIFY($PIECE(POINTS,",",P),10,2),! KILL POINTS,UP,LO,DIR,P,X QUIT
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.
#Free_Pascal
Free Pascal
program Bitwise; {$mode objfpc} var // Pascal uses a native int type as a default literal type // Make sure the operants work on an exact type. x:shortint = 2; y:ShortInt = 3; begin Writeln('2 and 3 = ', x and y); Writeln('2 or 3 = ', x or y); Writeln('2 xor 3 = ', x xor y); Writeln('not 2 = ', not x); Writeln('2 shl 3 = ', x >> y); Writeln('2 shr 3 = ', x << y); writeln('2 rol 3 = ', rolbyte(x,y)); writeln('2 ror 3 = ', rorbyte(x,y)); writeln('2 sar 3 = ', sarshortint(x,y)); Readln; end.
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixel with a color,   one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) These functions are used as a base for the articles in the category raster graphics operations, and a basic output function to check the results is available in the article write ppm file.
#Icon_and_Unicon
Icon and Unicon
procedure makebitmap(width,height) return open("bitmap", "g", "canvas=hidden", "size="||width||","||height) end procedure fillimage(w,color) Fg(w,color) FillRectangle(w) end procedure setpixel(w,x,y,color) Fg(w,color) DrawPixel(x,y) end procedure getpixel(w,x,y) return Pixel(w,x,y) end
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Little_Man_Computer
Little Man Computer
  // Little Man Computer, for Rosetta Code. // Calculate Bell numbers, using a 1-dimensional array and addition. // // After the calculation of B_n (n > 0), the array contains n elements, // of which B_n is the first. Example to show calculation of B_(n+1): // After calc. of B_3 = 5, array holds: 5, 3, 2 // Extend array by copying B_3 to high end: 5, 3, 2, 5 // Replace 2 by 5 + 2 = 7: 5, 3, 7, 5 // Replace 3 by 7 + 3 = 10: 5, 10, 7, 5 // Replace first 5 by 10 + 5 = 15: 15, 10, 7, 5 // First element of array is now B_4 = 15.   // Initialize; B_0 := 1 LDA c1 STA Bell LDA c0 STA index BRA print // skip increment of index // Increment index of Bell number inc_ix LDA index ADD c1 STA index // Here acc = index; print index and Bell number print OUT LDA colon OTC // non-standard instruction; cosmetic only LDA Bell OUT LDA index BRZ inc_ix // if index = 0, skip rest and loop back SUB c7 // reached maximum index yet? BRZ done // if so, jump to exit // Manufacture some instructions LDA lda_0 ADD index STA lda_ix SUB c200 // convert LDA to STA with same address STA sta_ix // Copy latest Bell number to end of array lda_0 LDA Bell // load Bell number sta_ix STA 0 // address was filled in above // Manufacture more instructions LDA lda_ix // load LDA instruction loop SUB c401 // convert to ADD with address 1 less STA add_ix_1 ADD c200 // convert to STA STA sta_ix_1 // Execute instructions; zero addresses were filled in above lda_ix LDA 0 // load element of array add_ix_1 ADD 0 // add to element below sta_ix_1 STA 0 // update element below LDA sta_ix_1 // load previous STA instruction SUB sta_Bell // does it refer to first element of array? BRZ inc_ix // yes, loop to inc index and print LDA lda_ix // no, repeat with addresses 1 less SUB c1 STA lda_ix BRA loop // Here when done done HLT // Constants colon DAT 58 c0 DAT 0 c1 DAT 1 c7 DAT 7 // maximum index c200 DAT 200 c401 DAT 401 sta_Bell STA Bell // not executed; used for comparison // Variables index DAT Bell DAT // Rest of array goes here // end  
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a} {b} is the same as {b} {a}. So B0 = 1 trivially. There is only one way to partition a set with zero elements. { } B1 = 1 There is only one way to partition a set with one element. {a} B2 = 2 Two elements may be partitioned in two ways. {a} {b}, {a b} B3 = 5 Three elements may be partitioned in five ways {a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c} and so on. A simple way to find the Bell numbers is construct a Bell triangle, also known as an Aitken's array or Peirce triangle, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. Task Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the first 15 and (if your language supports big Integers) 50th elements of the sequence. If you do use the Bell triangle method to generate the numbers, also show the first ten rows of the Bell triangle. See also OEIS:A000110 Bell or exponential numbers OEIS:A011971 Aitken's array
#Lua
Lua
-- Bell numbers in Lua -- db 6/11/2020 (to replace missing original)   local function bellTriangle(n) local tri = { {1} } for i = 2, n do tri[i] = { tri[i-1][i-1] } for j = 2, i do tri[i][j] = tri[i][j-1] + tri[i-1][j-1] end end return tri end   local N = 25 -- in lieu of 50, practical limit with double precision floats local tri = bellTriangle(N)   print("First 15 and "..N.."th Bell numbers:") for i = 1, 15 do print(i, tri[i][1]) end print(N, tri[N][1])   print()   print("First 10 rows of Bell triangle:") for i = 1, 10 do print("[ " .. table.concat(tri[i],", ") .. " ]") 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 .
#Go
Go
package main   import ( "fmt" "math" )   func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] }   func main() { show(Fib1000(), "First 1000 Fibonacci numbers") }   func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf("  %d  %9.3f  %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
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   +½.
#FreeBASIC
FreeBASIC
' version 08-10-2016 ' compile with: fbc -s console ' uses gmp   #Include Once "gmp.bi"   #Define max 60   Dim As Long n Dim As ZString Ptr gmp_str :gmp_str = Allocate(1000) ' 1000 char Dim Shared As Mpq_ptr tmp, big_j tmp = Allocate(Len(__mpq_struct)) :Mpq_init(tmp) big_j = Allocate(Len(__mpq_struct)) :Mpq_init(big_j)   Dim Shared As Mpq_ptr a(max), b(max) For n = 0 To max A(n) = Allocate(Len(__mpq_struct)) :Mpq_init(A(n)) B(n) = Allocate(Len(__mpq_struct)) :Mpq_init(B(n)) Next   Function Bernoulli(n As Integer) As Mpq_ptr   Dim As Long m, j   For m = 0 To n Mpq_set_ui(A(m), 1, m + 1) For j = m To 1 Step - 1 Mpq_sub(tmp, A(j - 1), A(j)) Mpq_set_ui(big_j, j, 1) 'big_j = j Mpq_mul(A(j - 1), big_j, tmp) Next Next   Return A(0) End Function   ' ------=< MAIN >=------   For n = 0 To max Mpq_set(B(n), Bernoulli(n)) Mpq_get_str(gmp_str, 10, B(n)) If *gmp_str <> "0" Then If *gmp_str = "1" Then *gmp_str = "1/1" Print Using "B(##) = "; n; Print Space(45 - InStr(*gmp_str, "/")); *gmp_str End If Next     ' empty keyboard buffer While Inkey <> "" :Wend Print :Print "hit any key to end program" Sleep 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.
#BASIC256
BASIC256
function binarySearchR(array, valor, lb, ub) if ub < lb then return false else mitad = floor((lb + ub) / 2) if valor < array[mitad] then return binarySearchR(array, valor, lb, mitad-1) if valor > array[mitad] then return binarySearchR(array, valor, mitad+1, ub) if valor = array[mitad] then return mitad end if end function
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
#Free_Pascal
Free Pascal
  Program BestShuffle;   Const arr : array[1..6] Of string = ('abracadabra','seesaw','elk','grrrrrr','up','a');   Function Shuffle(inp: String): STRING;   Var x,ReplacementDigit : longint; ch : char; Begin If length(inp) > 1 Then Begin Randomize; For x := 1 To length(inp) Do Begin Repeat ReplacementDigit := random(length(inp))+1; Until (ReplacementDigit <> x); ch := inp[x]; inp[x] := inp[ReplacementDigit]; inp[ReplacementDigit] := ch; End; End; shuffle := inp; End;     Function score(OrgString,ShuString : String) : integer;   Var i : integer; Begin score := 0; For i := 1 To length(OrgString) Do If OrgString[i] = ShuString[i] Then inc(score); End;   Var i : integer; shuffled : string; Begin For i := low(arr) To high(arr) Do Begin shuffled := shuffle(arr[i]); writeln(arr[i],' , ',shuffled,' , (',score(arr[i],shuffled),')'); 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.
#Liberty_BASIC
Liberty BASIC
  'string creation s$ = "Hello, world!"   'string destruction - not needed because of garbage collection s$ = ""   'string comparison s$ = "Hello, world!" If s$ = "Hello, world!" then print "Equal Strings"   'string copying a$ = s$   'check If empty If s$ = "" then print "Empty String"   'append a byte s$ = s$ + Chr$(33)   'extract a substring a$ = Mid$(s$, 1, 5)   'replace bytes a$ = "Hello, world!" for i = 1 to len(a$) if mid$(a$,i,1)="l" then a$=left$(a$,i-1)+"L"+mid$(a$,i+1) end if next print a$   'join strings s$ = "Good" + "bye" + " for now."  
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Rust
Rust
fn make_bins(limits: &Vec<usize>, data: &Vec<usize>) -> Vec<Vec<usize>> { let mut bins: Vec<Vec<usize>> = Vec::with_capacity(limits.len() + 1); for _ in 0..=limits.len() {bins.push(Vec::new());}   limits.iter().enumerate().for_each(|(idx, limit)| { data.iter().for_each(|elem| { if idx == 0 && elem < limit { bins[0].push(*elem); } // smaller than the smallest limit else if idx == limits.len()-1 && elem >= limit { bins[limits.len()].push(*elem); } // larger than the largest limit else if elem < limit && elem >= &limits[idx-1] { bins[idx].push(*elem); } // otherwise }); });   bins }   fn print_bins(limits: &Vec<usize>, bins: &Vec<Vec<usize>>) { for (idx, bin) in bins.iter().enumerate() { if idx == 0 { println!(" < {:3} := {:3}", limits[idx], bin.len()); } else if idx == limits.len() { println!(">= {:3}  := {:3}", limits[idx-1], bin.len()); }else { println!(">= {:3} .. < {:3} := {:3}", limits[idx-1], limits[idx], bin.len()); } }; }   fn main() { let limits1 = vec![23, 37, 43, 53, 67, 83]; let data1 = vec![95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55];   let limits2 = vec![14, 18, 249, 312, 389, 392, 513, 591, 634, 720]; let data2 = vec![ 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749 ];     // Why are we calling it RC anyways??? println!("RC FIRST EXAMPLE"); let bins1 = make_bins(&limits1, &data1); print_bins(&limits1, &bins1);   println!("\nRC SECOND EXAMPLE"); let bins2 = make_bins(&limits2, &data2); print_bins(&limits2, &bins2); }  
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] .. bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] Task The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will print the limit of each bin together with the count of items that fell in the range. Assume the numbers to bin are too large to practically sort. Task examples Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
#Tcl
Tcl
namespace path {::tcl::mathop ::tcl::mathfunc}   # Not necessary but useful helper proc lincr {_list index} { upvar $_list list lset list $index [+ [lindex $list $index] 1] }   proc distribute_bins {binlims data} { set bins [lrepeat [+ [llength $binlims] 1] 0] foreach val $data { lincr bins [+ [lsearch -exact -integer -sorted -bisect $binlims $val] 1] } return $bins }   proc print_bins {binlims bins} { set binlims [list -∞ {*}$binlims ∞] for {set i 0} {$i < [llength $bins]} {incr i} { puts "[lindex $binlims $i]..[lindex $binlims [+ $i 1]]: [lindex $bins $i]" } }   set binlims {23 37 43 53 67 83} set data {95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55} print_bins $binlims [distribute_bins $binlims $data] puts ""   set binlims {14 18 249 312 389 392 513 591 634 720} set data {445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933 416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306 655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247 346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123 345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97 854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395 787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692 698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237 605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791 466 23 707 467 33 670 921 180 991 396 160 436 717 918 8 374 101 684 727 749} print_bins $binlims [distribute_bins $binlims $data]
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#XPL0
XPL0
char Bases; int Counts(256), Cnt, I, Ch; [Bases:= " CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAATx ";   for I:= 0 to 255 do Counts(I):= 0; Format(5, 0); Cnt:= 0; I:= 0; loop [repeat Ch:= Bases(I); I:= I+1; if Ch = ^x then quit; Counts(Ch):= Counts(Ch)+1; ChOut(0, Ch); until Ch = \LF\$0A; RlOut(0, float(Cnt)); Text(0, ": "); Cnt:= Cnt + 50; ]; CrLf(0); CrLf(0); Text(0, "Base counts A: "); IntOut(0, Counts(^A)); Text(0, " C: "); IntOut(0, Counts(^C)); Text(0, " G: "); IntOut(0, Counts(^G)); Text(0, " T: "); IntOut(0, Counts(^T)); Text(0, " Total: "); IntOut(0, Cnt); CrLf(0); ]
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
bases:= #<<<" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - " \n"; #<<<   [0..*,50].zipWith(fcn(n,bases){ println("%6d: %s".fmt(n,bases.concat())) }, bases.walker().walk.fp(50)).pump(Void); // .pump forces the iterator   println("\nBase Counts: ", bases.counts().pump(String,Void.Read,"%s: %d ".fmt)); println("Total: ",bases.len());
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.
#AutoIt
AutoIt
  ConsoleWrite(IntToBin(50) & @CRLF)   Func IntToBin($iInt) $Stack = ObjCreate("System.Collections.Stack") Local $b = -1, $r = "" While $iInt <> 0 $b = Mod($iInt, 2) $iInt = INT($iInt/2) $Stack.Push ($b) WEnd For $i = 1 TO $Stack.Count $r &= $Stack.Pop Next Return $r EndFunc ;==>IntToBin  
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.
#Julia
Julia
function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T δx = abs(x1 - x0) δy = abs(y1 - y0) δe = abs(δy / δx) er = 0.0   y = y0 for x in x0:x1 img[x, y] = col er += δe if er > 0.5 y += 1 er -= 1.0 end end   return img end   using Images   img = fill(Gray(255.0), 5, 5); println("\nImage:") display(img); println() drawline!(img, 1, 1, 5, 5, Gray(0.0)); println("\nModified image:") display(img); println()
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
#Pike
Pike
  > 0; (3) Result: 0 > false; (4) Result: 0 > 0; (6) Result: 0 > !true; (7) Result: 0 > true; (8) Result: 1 > 1; (9) Result: 1 >  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PL.2FI
PL/I
Declare x bit(1); x='1'b; /* True */ x='0'b; /* False */
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). Notes; The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary utf8   class RCBoxTheCompass   properties public constant _FULL = '_FULL'   properties indirect headings = Rexx rosepoints = Rexx   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method RCBoxTheCompass() public   setHeadings(makeHeadings) setRosepoints(makeRosepoints)   return   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method main(args = String[]) public static   box = RCBoxTheCompass()   cp = box.getCompassPoints loop r_ = 1 to cp[0] say cp[r_] end r_ say   hx = box.getHeadingsReport(box.getHeadings) loop r_ = 1 to hx[0] say hx[r_] end r_ say   return   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getDecimalAngle(degrees, minutes, seconds) public static returns Rexx   degrees = degrees * 10 % 10 minutes = minutes * 10 % 10 angle = degrees + (minutes / 60 + (seconds / 60 / 60))   return angle   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getDegreesMinutesSeconds(angle) public static returns Rexx   degrees = angle * 100 % 100 minutes = ((angle - degrees) * 60) * 100 % 100 seconds = ((((angle - degrees) * 60) - minutes) * 60) * 100 % 100   return degrees minutes seconds   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getHeadingsReport(bearings) public returns Rexx   r_ = 0 table = '' r_ = r_ + 1; table[0] = r_; table[r_] = 'Idx' - 'Abbr' - 'Compass Point'.left(20) - 'Degrees'.right(10)   loop h_ = 1 to bearings[0] heading = bearings[h_] index = getRosepointIndex(heading) parse getRosepoint(index) p_abbrev p_full   r_ = r_ + 1; table[0] = r_; table[r_] = index.right(3) - p_abbrev.left(4) - p_full.left(20) - heading.format(6, 3).right(10) end h_   return table   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getRosepointIndex(heading) public returns Rexx   one_pt = 360 / 32 hn = heading // 360 hi = hn % one_pt   if hn > hi * one_pt + one_pt / 2 then do hi = hi + 1 -- greater than max range for this point; bump to next point end   idx = hi // 32 + 1 -- add one to get index into rosepoints indexed string   return idx   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getRosepoint(index) public returns Rexx   rp = getRosepoints return rp[index] rp[index, _FULL]   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method makeRosepoints() private returns Rexx   p_ = 0 rp = '' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'N'; rp[p_, _FULL] = 'North' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NbE'; rp[p_, _FULL] = 'North by East' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NNE'; rp[p_, _FULL] = 'North-Northeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NEbn'; rp[p_, _FULL] = 'Northeast by North' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NE'; rp[p_, _FULL] = 'Northeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NEbE'; rp[p_, _FULL] = 'Northeast by East' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'ENE'; rp[p_, _FULL] = 'East-Northeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'EbN'; rp[p_, _FULL] = 'East by North' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'E'; rp[p_, _FULL] = 'East' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'EbS'; rp[p_, _FULL] = 'East by South' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'ESE'; rp[p_, _FULL] = 'East-Southeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SEbE'; rp[p_, _FULL] = 'Southeast by East' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SE'; rp[p_, _FULL] = 'Southeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SEbS'; rp[p_, _FULL] = 'Southeast by South' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SSE'; rp[p_, _FULL] = 'South-Southeast' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SbE'; rp[p_, _FULL] = 'South by East' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'S'; rp[p_, _FULL] = 'South' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SbW'; rp[p_, _FULL] = 'South by West' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SSW'; rp[p_, _FULL] = 'South-Southwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SWbS'; rp[p_, _FULL] = 'Southwest by South' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SW'; rp[p_, _FULL] = 'Southwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'SWbW'; rp[p_, _FULL] = 'Southwest by West' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'WSW'; rp[p_, _FULL] = 'Southwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'WbS'; rp[p_, _FULL] = 'West by South' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'W'; rp[p_, _FULL] = 'West' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'WbN'; rp[p_, _FULL] = 'West by North' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'WNW'; rp[p_, _FULL] = 'West-Northwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NWbW'; rp[p_, _FULL] = 'Northwest by West' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NW'; rp[p_, _FULL] = 'Northwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NWbN'; rp[p_, _FULL] = 'Northwest by North' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NNW'; rp[p_, _FULL] = 'North-Northwest' p_ = p_ + 1; rp[0] = p_; rp[p_] = 'NbW'; rp[p_, _FULL] = 'North by West'   return rp   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method makeHeadings() private returns Rexx   hdg = '' hdg[0] = 0 points = 32 loop i_ = 0 to points heading = i_ * 360 / points   select case i_ // 3 when 1 then heading_h = heading + 5.62 when 2 then heading_h = heading - 5.62 otherwise heading_h = heading end   ix = hdg[0] + 1; hdg[0] = ix; hdg[ix] = heading_h end i_   return hdg   /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ method getCompassPoints() public returns Rexx   r_ = 0 table = '' r_ = r_ + 1; table[0] = r_; table[r_] = 'Idx' - 'Abbr' - 'Compass Point'.left(20) - 'Low (Deg.)'.right(10) - 'Mid (Deg.)'.right(10) - 'Hi (Deg.)'.right(10)   -- one point of the compass is 360 / 32 (11.25) degrees -- using functions to calculate this just for fun one_pt = 360 / 32 parse getDegreesMinutesSeconds(one_pt / 2) ad am as . points = 32 loop h_ = 0 to points - 1 heading = h_ * 360 / points hmin = heading - getDecimalAngle(ad, am, as) hmax = heading + getDecimalAngle(ad, am, as)   if hmin < 0 then do hmin = hmin + 360 end if hmax >= 360 then do hmax = hmax - 360 end   index = getRosepointIndex(heading) parse getRosepoint(index) p_abbrev p_full r_ = r_ + 1; table[0] = r_; table[r_] = index.right(3) - p_abbrev.left(4) - p_full.left(20) - hmin.format(6, 3).right(10) - heading.format(6, 3).right(10) - hmax.format(6, 3).right(10) end h_   return table