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/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
#LabVIEW
LabVIEW
  {if true then YES else NO} -> YES {if false then YES else NO} -> NO  
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
#Lambdatalk
Lambdatalk
  {if true then YES else NO} -> YES {if false then YES else NO} -> NO  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#zonnon
zonnon
  module Caesar; const size = 25;   type Operation = (code,decode);   procedure C_D(s:string;k:integer;op: Operation): string; var i,key: integer; resp: string; n,c: char; begin resp := ""; if op = Operation.decode then key := k else key := (26 - k) end; for i := 0 to len(s) - 1 do c := cap(s[i]); if (c >= 'A') & (c <= 'Z') then resp := resp + string(char(integer('A') + ((integer(c) - integer('A') + key )) mod 26)); else resp := resp + string(c) end; end; return resp end C_D;   procedure {public} Cipher(s:string;k:integer):string; var i: integer; resp: string; n,c: char; begin return C_D(s,k,Operation.code) end Cipher;   procedure {public} Decipher(s:string;k:integer):string; var i: integer; resp: string; n,c: char; begin return C_D(s,k,Operation.decode) end Decipher;   var txt,cipher,decipher: string;   begin txt := "HI";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2); writeln(txt," -c-> ",cipher," -d-> ",decipher); txt := "ZA";cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2); writeln(txt," -c-> ",cipher," -d-> ",decipher); txt := "The five boxing wizards jump quickly"; cipher := Caesar.Cipher(txt,2);decipher := Caesar.Decipher(cipher,2); writeln(txt," -c-> ",cipher," -d-> ",decipher) end Caesar.  
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)..
#Huginn
Huginn
import Algorithms as algo; import Text as text;   class Compass { _majors = none; _quarter1 = none; _quarter2 = none; constructor() { _majors = algo.materialize( text.split( "north east south west", " " ), tuple ); _majors += _majors; _quarter1 = text.split( "N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N", "," ); _quarter2 = algo.materialize( algo.map( _quarter1, @( s ){ copy( s ).replace( "NE", "EN" ); } ), list ); } degrees_to_compasspoint( d ) { d = d % 360. + 360. / 64.; majorindex, minor = ( integer( d ) / 90, d % 90. ); minorindex = integer( minor * 4. ) / 45; p1, p2 = _majors[majorindex: majorindex + 2]; q = none; if ( p1 ∈ { "north", "south" } ) { q = _quarter1; } else { q = _quarter2; } return ( text.capitalize( copy( q[minorindex] ).replace( "N", p1 ).replace( "E", p2 ) ) ); } }   main() { print( " # | Angle | Compass point\n" "---+---------|-------------------\n" ); c = Compass(); for ( i : algo.range( 33 ) ) { d = real( i ) * 11.25; m = i % 3; if ( m == 1 ) { d += 5.62; } else if ( m == 2 ) { d -= 5.62; } n = i % 32 + 1; print( "{:2d} | {:6.2f}° | {}\n".format( n, d, c.degrees_to_compasspoint( d ) ) ); } }
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Write a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate. All shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer. If any operation is not available in your language, note it.
#C.23
C#
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); // When the left operand of the >> operator is of a signed integral type, // the operator performs an arithmetic shift right uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); // When the left operand of the >> operator is of an unsigned integral type, // the operator performs a logical shift right // there are no rotation operators in C# }
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.
#C.2B.2B
C++
#include <iostream> #include <boost/gil/gil_all.hpp> int main() { using namespace boost::gil; // create 30x40 image rgb8_image_t img(30, 40);   // fill with red rgb8_pixel_t red(255, 0, 0); fill_pixels(view(img), red);   // set pixel at 10x20 to blue rgb8_pixel_t blue(0, 0, 255); view(img)(10, 20) = blue;   // read the value of pixel at 11x20 rgb8_pixel_t px = const_view(img)(11, 20); std::cout << "the pixel at 11, 20 is " << (unsigned)px[0] << ':' << (unsigned)px[1] << ':' << (unsigned)px[2] << '\n'; }
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   proc Bezier(P0, P1, P2, P3); \Draw cubic Bezier curve real P0, P1, P2, P3; def Segments = 8; int I; real S1, T, T2, T3, U, U2, U3, B, C, X, Y; [Move(fix(P0(0)), fix(P0(1))); S1:= 1./float(Segments); T:= 0.; for I:= 1 to Segments-1 do [T:= T+S1; T2:= T*T; T3:= T2*T; U:= 1.-T; U2:= U*U; U3:= U2*U; B:= 3.*T*U2; C:= 3.*T2*U; X:= U3*P0(0) + B*P1(0) + C*P2(0) + T3*P3(0); Y:= U3*P0(1) + B*P1(1) + C*P2(1) + T3*P3(1); Line(fix(X), fix(Y), $00FFFF); \cyan line segments ]; Line(fix(P3(0)), fix(P3(1)), $00FFFF); Point(fix(P0(0)), fix(P0(1)), $FF0000); \red control points Point(fix(P1(0)), fix(P1(1)), $FF0000); Point(fix(P2(0)), fix(P2(1)), $FF0000); Point(fix(P3(0)), fix(P3(1)), $FF0000); ];   [SetVid($112); \set 640x480x24 video graphics Bezier([0., 0.], [30., 100.], [120., 20.], [160., 120.]); if ChIn(1) then []; \wait for keystroke SetVid(3); \restore normal text display ]
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#zkl
zkl
fcn cBezier(p0x,p0y, p1x,p1y, p2x,p2y, p3x,p3y, rgb, numPts=500){ numPts.pump(Void,'wrap(t){ // B(t) t=t.toFloat()/numPts; t1:=(1.0 - t); a:=t1*t1*t1; b:=t*t1*t1*3; c:=t1*t*t*3; d:=t*t*t; x:=a*p0x + b*p1x + c*p2x + d*p3x + 0.5; y:=a*p0y + b*p1y + c*p2y + d*p3y + 0.5; __sSet(rgb,x,y); }); }
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple. It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous! To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. The three cycles and their lengths are as follows: Cycle Length Physical 23 days Emotional 28 days Mental 33 days The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory. The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice. Example run of my Raku implementation: raku br.raku 1943-03-09 1972-07-11 Output: Day 10717: Physical day 22: -27% (down but rising, next transition 1972-07-12) Emotional day 21: valley Mental day 25: valley Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
#VBA
VBA
Function Biorhythm(Birthdate As Date, Targetdate As Date) As String   'Jagged Array TextArray = Array(Array("up and rising", "peak"), Array("up but falling", "transition"), Array("down and falling", "valley"), Array("down but rising", "transition"))   DaysBetween = Targetdate - Birthdate   positionP = DaysBetween Mod 23 positionE = DaysBetween Mod 28 positionM = DaysBetween Mod 33   'return the positions - just to return something Biorhythm = CStr(positionP) & "/" & CStr(positionE) & "/" & CStr(positionM)   quadrantP = Int(4 * positionP / 23) quadrantE = Int(4 * positionE / 28) quadrantM = Int(4 * positionM / 33)   percentageP = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionP / 23)), 1) percentageE = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionE / 28)), 1) percentageM = Round(100 * Sin(2 * WorksheetFunction.Pi * (positionM / 33)), 1)   transitionP = Targetdate + WorksheetFunction.Floor((quadrantP + 1) / 4 * 23, 1) - positionP transitionE = Targetdate + WorksheetFunction.Floor((quadrantE + 1) / 4 * 28, 1) - positionE transitionM = Targetdate + WorksheetFunction.Floor((quadrantM + 1) / 4 * 33, 1) - positionM   Select Case True Case percentageP > 95 textP = "Physical day " & positionP & " : " & "peak" Case percentageP < -95 textP = "Physical day " & positionP & " : " & "valley" Case percentageP < 5 And percentageP > -5 textP = "Physical day " & positionP & " : " & "critical transition" Case Else textP = "Physical day " & positionP & " : " & percentageP & "% (" & TextArray(quadrantP)(0) & ", next " & TextArray(quadrantP)(1) & " " & transitionP & ")" End Select   Select Case True Case percentageE > 95 textE = "Emotional day " & positionE & " : " & "peak" Case percentageE < -95 textE = "Emotional day " & positionE & " : " & "valley" Case percentageE < 5 And percentageE > -5 textE = "Emotional day " & positionE & " : " & "critical transition" Case Else textE = "Emotional day " & positionE & " : " & percentageE & "% (" & TextArray(quadrantE)(0) & ", next " & TextArray(quadrantE)(1) & " " & transitionE & ")" End Select   Select Case True Case percentageM > 95 textM = "Mental day " & positionM & " : " & "peak" Case percentageM < -95 textM = "Mental day " & positionM & " : " & "valley" Case percentageM < 5 And percentageM > -5 textM = "Mental day " & positionM & " : " & "critical transition" Case Else textM = "Mental day " & positionM & " : " & percentageM & "% (" & TextArray(quadrantM)(0) & ", next " & TextArray(quadrantM)(1) & " " & transitionM & ")" End Select   Header1Text = "Born " & Birthdate & ", Target " & Targetdate Header2Text = "Day " & DaysBetween   'Print Result Debug.Print Header1Text Debug.Print Header2Text Debug.Print textP Debug.Print textE Debug.Print textM Debug.Print ""   End Function
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple. It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous! To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. The three cycles and their lengths are as follows: Cycle Length Physical 23 days Emotional 28 days Mental 33 days The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory. The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice. Example run of my Raku implementation: raku br.raku 1943-03-09 1972-07-11 Output: Day 10717: Physical day 22: -27% (down but rising, next transition 1972-07-12) Emotional day 21: valley Mental day 25: valley Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
#Vlang
Vlang
import time import math   const cycles = ["Physical day ", "Emotional day", "Mental day "] const lengths = [23, 28, 33] const quadrants = [ ["up and rising", "peak"], ["up but falling", "transition"], ["down and falling", "valley"], ["down but rising", "transition"], ]   // Parameters assumed to be in YYYY-MM-DD format. fn biorhythms(birth_date string, target_date string) ? { bd := time.parse_iso8601(birth_date)? td := time.parse_iso8601(target_date)? days := int((td-bd).hours() / 24) println("Born $birth_date, Target $target_date") println("Day $days") for i in 0..3 { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length mut percent := math.sin(2 * math.pi * f64(position) / f64(length)) percent = math.floor(percent*1000) / 10 mut descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.abs(percent) < 5 { descript = " critical transition" } else { days_to_add := (quadrant+1)*length/4 - position transition := td.add(time.hour * 24 * time.Duration(days_to_add)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] trans_str := transition.custom_format('YYYY-MM-DD') descript = "${percent:5.1f}% ($trend, next $next $trans_str)" } println("$cycle ${position:2} : $descript") } println('') }   fn main() { date_pairs := [ ["1943-03-09", "1972-07-11"], ["1809-01-12", "1863-11-19"], ["1809-02-12", "1863-11-19"], // correct DOB for Abraham Lincoln ] for date_pair in date_pairs { biorhythms(date_pair[0], date_pair[1])? } }
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
#11l
11l
F bellTriangle(n) [[BigInt]] tri L(i) 0 .< n tri.append([BigInt(0)] * i) tri[1][0] = 1 L(i) 2 .< n tri[i][0] = tri[i - 1][i - 2] L(j) 1 .< i tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] R tri   V bt = bellTriangle(51) print(‘First fifteen and fiftieth Bell numbers:’) L(i) 1..15 print(‘#2: #.’.format(i, bt[i][0])) print(‘50: ’bt[50][0]) print() print(‘The first ten rows of Bell's triangle:’) L(i) 1..10 print(bt[i])
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.
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { # string creation a="123\0 abc "; b="456\x09"; c="789"; printf("abc=<%s><%s><%s>\n",a,b,c);   # string comparison printf("(a==b) is %i\n",a==b)   # string copying A = a; B = b; C = c; printf("ABC=<%s><%s><%s>\n",A,B,C);   # check if string is empty if (length(a)==0) { printf("string a is empty\n"); } else { printf("string a is not empty\n"); }   # append a byte to a string a=a"\x40"; printf("abc=<%s><%s><%s>\n",a,b,c);   # substring e = substr(a,1,6); printf("substr(a,1,6)=<%s>\n",e);   # join strings d=a""b""c; printf("d=<%s>\n",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.
#C
C
#include <stdio.h> #include <stdlib.h>   size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; }   int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; }   void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(" < %3d: %2d\n", limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(">= %3d and < %3d: %2d\n", limits[i - 1], limits[i], bins[i]); printf(">= %3d  : %2d\n", limits[n - 1], bins[n]); }   int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};   printf("Example 1:\n"); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b);   const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749};   printf("\nExample 2:\n"); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, "Out of memory\n"); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b);   return EXIT_SUCCESS; }
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
#Go
Go
package main   import ( "fmt" "sort" )   func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += 50 { k := i + 50 if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) // allows for 'any' base for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order return bases[i] < bases[j] })   fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf("  %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======") }
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.
#11l
11l
L(n) [0, 5, 50, 9000] print(‘#4 = #.’.format(n, bin(n)))
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Common_Lisp
Common Lisp
(defun draw-line (buffer x1 y1 x2 y2 pixel) (declare (type rgb-pixel-buffer buffer)) (declare (type integer x1 y1 x2 y2)) (declare (type rgb-pixel pixel)) (let* ((dist-x (abs (- x1 x2))) (dist-y (abs (- y1 y2))) (steep (> dist-y dist-x))) (when steep (psetf x1 y1 y1 x1 x2 y2 y2 x2)) (when (> x1 x2) (psetf x1 x2 x2 x1 y1 y2 y2 y1)) (let* ((delta-x (- x2 x1)) (delta-y (abs (- y1 y2))) (error (floor delta-x 2)) (y-step (if (< y1 y2) 1 -1)) (y y1)) (loop :for x :upfrom x1 :to x2 :do (if steep (setf (rgb-pixel buffer x y) pixel) (setf (rgb-pixel buffer y x) pixel)) (setf error (- error delta-y)) (when (< error 0) (incf y y-step) (incf error delta-x)))) buffer))
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) Delete the chosen base at the position. Insert another base randomly chosen from A,C, G, or T into the sequence at that position. Randomly generate a test DNA sequence of at least 200 bases "Pretty print" the sequence and a count of its size, and the count of each base in the sequence Mutate the sequence ten times. "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. Extra credit Give more information on the individual mutations applied. Allow mutations to be weighted and/or chosen.
#Phix
Phix
string dna = repeat(' ',200+rand(300)) for i=1 to length(dna) do dna[i] = "ACGT"[rand(4)] end for procedure show() sequence acgt = repeat(0,5) for i=1 to length(dna) do acgt[find(dna[i],"ACGT")] += 1 end for acgt[$] = sum(acgt) sequence s = split(trim(join_by(split(join_by(dna,1,10,""),"\n"),1,5," ")),"\n") for i=1 to length(s) do printf(1,"%3d: %s\n",{(i-1)*50+1,s[i]}) end for printf(1,"\nBase counts: A:%d, C:%d, G:%d, T:%d, total:%d\n",acgt) end procedure procedure mutate() printf(1,"\n") for i=1 to 10 do integer p = rand(length(dna)), sdi = "SDI"[rand(3)], rep = "ACGT"[rand(4)], was = dna[p] switch sdi do case 'S':dna[p] = rep printf(1,"swapped %c at %d for %c\n",{was,p,rep}) case 'D':dna[p..p] = "" printf(1,"deleted %c at %d\n",{was,p}) case 'I':dna[p..p-1] = ""&rep printf(1,"inserted %c at %d, before %c\n",{rep,p,was}) end switch end for printf(1,"\n") end procedure show() mutate() show()
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Python
Python
from hashlib import sha256   digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'   def decode_base58(bc, length): n = 0 for char in bc: n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big') def check_bc(bc): try: bcbytes = decode_base58(bc, 25) return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] except Exception: return False   print(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i')) print(check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j"))
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Racket
Racket
  #lang racket/base   ;; Same sha-256 interface as the same-named task (require ffi/unsafe ffi/unsafe/define openssl/libcrypto) (define-ffi-definer defcrypto libcrypto) (defcrypto SHA256_Init (_fun _pointer -> _int)) (defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) (defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) (define (sha256 bytes) (define ctx (malloc 128)) (define result (make-bytes 32)) (SHA256_Init ctx) (SHA256_Update ctx bytes (bytes-length bytes)) (SHA256_Final result ctx) result)   ;; base58 decoding (define base58-digits (let ([v (make-vector 128 #f)]) (for ([i (in-naturals)] [c "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"]) (vector-set! v (char->integer c) i)) v)) (define (base58->integer str) (for/fold ([n 0]) ([c str]) (+ (* n 58) (vector-ref base58-digits (char->integer c)))))   (define (int->bytes n digits) (list->bytes (let loop ([n n] [digits digits] [acc '()]) (if (zero? digits) acc (let-values ([(q r) (quotient/remainder n 256)]) (loop q (sub1 digits) (cons r acc)))))))   (define (validate-bitcoin-address str) (define bs (int->bytes (base58->integer str) 25)) (equal? (subbytes (sha256 (sha256 (subbytes bs 0 21))) 0 4) (subbytes bs 21)))   ;; additional tests taken from the other solutions (validate-bitcoin-address "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i") ; => #t (validate-bitcoin-address "1111111111111111111114oLvT2")  ; => #t (validate-bitcoin-address "17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j") ; => #t (validate-bitcoin-address "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9") ; => #t (validate-bitcoin-address "1badbadbadbadbadbadbadbadbadbadbad") ; => #f  
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Perl
Perl
#! /usr/bin/perl   use strict; use Image::Imlib2;   my $img = Image::Imlib2->load("Unfilledcirc.jpg"); $img->set_color(0, 255, 0, 255); $img->fill(100,100); $img->save("filledcirc.jpg"); exit 0;
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Phix
Phix
-- demo\rosetta\Bitmap_FloodFill.exw (runnable version) include ppm.e -- blue, green, read_ppm(), write_ppm() (covers above requirements)   function ff(sequence img, integer x, y, colour, target) if x>=1 and x<=length(img) and y>=1 and y<=length(img[x]) and img[x][y]=target then img[x][y] = colour img = ff(img,x-1,y,colour,target) img = ff(img,x+1,y,colour,target) img = ff(img,x,y-1,colour,target) img = ff(img,x,y+1,colour,target) end if return img end function   function FloodFill(sequence img, integer x, y, colour) integer target = img[x][y] return ff(img,x,y,colour,target) end function   sequence img = read_ppm("Circle.ppm") img = FloodFill(img, 200, 100, blue) write_ppm("FloodIn.ppm",img) img = FloodFill(img, 10, 10, green) write_ppm("FloodOut.ppm",img)
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Lasso
Lasso
!true // => false   not false // => true   var(x = true) $x // => true   $x = false $x // => 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
#Latitude
Latitude
  > 'true true > 'false false > (or 'false 'false) false > (or 'false 'true) true  
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET t$="PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS" 20 PRINT t$'' 30 LET key=RND*25+1 40 LET k=key: GO SUB 1000: PRINT t$'' 50 LET k=26-key: GO SUB 1000: PRINT t$ 60 STOP 1000 FOR i=1 TO LEN t$ 1010 LET c= CODE t$(i) 1020 IF c<65 OR c>90 THEN GO TO 1050 1030 LET c=c+k: IF c>90 THEN LET c=c-90+64 1040 LET t$(i)=CHR$ c 1050 NEXT i 1060 RETURN  
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)..
#Icon_and_Unicon
Icon and Unicon
link strings,numbers   procedure main()   every heading := 11.25 * (i := 0 to 32) do { case i%3 of { 1: heading +:= 5.62 2: heading -:= 5.62 } write(right(i+1,3)," ",left(direction(heading),20)," ",fix(heading,,7,2)) } end   procedure direction(d) # compass heading given +/- degrees static dirs initial { every put(dirs := [], replacem(!["N","NbE","N-NE","NEbN","NE","NEbE","E-NE","EbN", "E","EbS","E-SE","SEbE","SE","SEbS","S-SE","SbE", "S","SbW","S-SW","SWbS","SW","SWbW","W-SW","WbS", "W","WbN","W-NW","NWbW","NW","NWbN","N-NW","NbW"], "N","north","E","east","W","west","S","south","b"," by ")) }   return dirs[round(((((d%360)+360)%360)/11.25)%32 + 1)] 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.
#C.2B.2B
C++
#include <iostream>   void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than << std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n';   // Note: the C/C++ shift operators are not guaranteed to work if the shift count (that is, b) // is negative, or is greater or equal to the number of bits in the integer being shifted. std::cout << "a shl b: " << (a << b) << '\n'; // Note: "<<" is used both for output and for left shift std::cout << "a shr b: " << (a >> b) << '\n'; // typically arithmetic right shift, but not guaranteed unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; // logical right shift (guaranteed)   // there are no rotation operators in C++, but as of c++20 there is a standard-library rotate function. // The rotate function works for all rotation amounts, but the integer being rotated must always be an // unsigned integer. std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n';   }
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.
#Clojure
Clojure
(import '[java.awt Color Graphics Image] '[java.awt.image BufferedImage])   (defn blank-bitmap [width height] (BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR))   (defn fill [image color] (doto (.getGraphics image) (.setColor color) (.fillRect 0 0 (.getWidth image) (.getHeight image))))   (defn set-pixel [image x y color] (.setRGB image x y (.getRGB color)))   (defn get-pixel [image x y] (Color. (.getRGB image x y)))
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple. It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous! To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. The three cycles and their lengths are as follows: Cycle Length Physical 23 days Emotional 28 days Mental 33 days The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the kth day of an n-day cycle by computing sin( 2πk / n ). The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory. The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice. Example run of my Raku implementation: raku br.raku 1943-03-09 1972-07-11 Output: Day 10717: Physical day 22: -27% (down but rising, next transition 1972-07-12) Emotional day 21: valley Mental day 25: valley Double valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament...
#Wren
Wren
import "/date" for Date import "/fmt" for Fmt   var cycles = ["Physical day ", "Emotional day", "Mental day "] var lengths = [23, 28, 33] var quadrants = [ ["up and rising", "peak"], ["up but falling", "transition"], ["down and falling", "valley"], ["down but rising", "transition"] ]   var biorhythms = Fn.new { |birthDate, targetDate| var bd = Date.parse(birthDate) var td = Date.parse(targetDate) var days = (td - bd).days Date.default = Date.isoDate System.print("Born %(birthDate), Target %(targetDate)") System.print("Day %(days)") for (i in 0..2) { var length = lengths[i] var cycle = cycles[i] var position = days % length var quadrant = (position / length * 4).floor var percent = ((2 * Num.pi * position / length).sin * 1000).floor / 10 var descript = (percent > 95) ? " peak" : (percent < -95) ? " valley" : (percent.abs < 5) ? " critical transition" : "other" if (descript == "other") { var transition = td.addDays(((quadrant + 1) / 4 * length).floor - position) var tn = quadrants[quadrant] var trend = tn[0] var next = tn[1] descript = Fmt.swrite("$5.1f\% ($s, next $s $s)", percent, trend, next, transition) } Fmt.print("$s $2d : $s", cycle, position, descript) } System.print() }   var datePairs = [ ["1943-03-09", "1972-07-11"], ["1809-01-12", "1863-11-19"], ["1809-02-12", "1863-11-19"] // correct DOB for Abraham Lincoln ] for (datePair in datePairs) biorhythms.call(datePair[0], datePair[1])
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
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; procedure Main is type Bell_Triangle is array(Positive range <>, Positive range <>) of Natural;     procedure Print_Rows (Row : in Positive; Triangle : in Bell_Triangle) is begin if Row in Triangle'Range(1) then for I in Triangle'First(1) .. Row loop Put_Line (Triangle (I, 1)'Image); end loop; end if; end Print_Rows;   procedure Print_Triangle (Num : in Positive; Triangle : in Bell_Triangle) is begin if Num in Triangle'Range then for I in Triangle'First(1) .. Num loop for J in Triangle'First(2) .. Num loop if Triangle (I, J) /= 0 then Put (Triangle (I, J)'Image); end if; end loop; New_Line; end loop; end if; end Print_Triangle;   procedure Bell_Numbers is Triangle : Bell_Triangle(1..15, 1..15) := (Others => (Others => 0)); Temp  : Positive := 1; begin   Triangle (1, 1) := 1;   for I in Triangle'First(1) + 1 .. Triangle'Last(1) loop Triangle (I, 1) := Temp;   for J in Triangle'First(2) .. Triangle'Last(2) - 1 loop if Triangle (I - 1, J) /= 0 then Triangle (I, J + 1) := Triangle (I, J) + Triangle (I - 1, J); else Temp := Triangle (I, J); exit; end if; end loop; end loop;   Put_Line ("First 15 Bell numbers:"); Print_Rows (15, Triangle);   New_Line;   Put_Line ("First 10 rows of the Bell triangle:"); Print_Triangle (10, Triangle); end Bell_Numbers; begin Bell_Numbers; end Main;  
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#11l
11l
F get_fibs() V a = 1.0 V b = 1.0 [Float] r L 1000 r [+]= a (a, b) = (b, a + b) R r   F benford(seq) V freqs = [(0.0, 0.0)] * 9 V seq_len = 0 L(d) seq I d != 0 freqs[String(d)[0].code - ‘1’.code][1]++ seq_len++   L(&f) freqs f = (log10(1.0 + 1.0 / (L.index + 1)), f[1] / seq_len) R freqs   print(‘#9 #9 #9’.format(‘Actual’, ‘Expected’, ‘Deviation’))   L(p) benford(get_fibs()) print(‘#.: #2.2% | #2.2% | #.4%’.format(L.index + 1, p[1] * 100, p[0] * 100, abs(p[1] - p[0]) * 100))
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.
#BASIC
BASIC
REM STRING CREATION AND DESTRUCTION (WHEN NEEDED AND IF THERE'S NO GARBAGE COLLECTION OR SIMILAR MECHANISM) A$ = "STRING" : REM CREATION A$ = "" : REM DESTRUCTION PRINT FRE(0) : REM GARBAGE COLLECTION   REM STRING ASSIGNMENT A$ = "STRING" : R$ = "DEUX"   REM STRING COMPARISON PRINT A$ = B$; A$ <> B$; A$ < B$; A$ > B$; A$ <= B$; A$ >= B$   REM STRING CLONING AND COPYING B$ = A$   REM CHECK IF A STRING IS EMPTY PRINT LEN(A$) = 0   REM APPEND A BYTE TO A STRING A$ = A$ + CHR$(0)   REM EXTRACT A SUBSTRING FROM A STRING S$ = MID$(A$, 2, 3)   REM REPLACE EVERY OCCURRENCE OF A BYTE (OR A STRING) IN A STRING WITH ANOTHER STRING S = LEN(S$) : R = LEN(R$) : A = LEN(A$) : IF A > S THEN B$ = "" : FOR I = 1 TO A : F = MID$(A$, I, S) = S$ : B$ = B$ + MID$(R$, 1, R * F) + MID$(A$, I, F = 0) : NEXT I : A$ = B$ : PRINT A$   REM JOIN STRINGS J$ = A$ + STR$(42) + " PUDDLES " + B$ + CHR$(255) : REM USE +
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.
#BBC_BASIC
BBC BASIC
A$ = CHR$(0) + CHR$(1) + CHR$(254) + CHR$(255) : REM assignment B$ = A$  : REM clone / copy IF A$ = B$ THEN PRINT "Strings are equal"  : REM comparison IF A$ = "" THEN PRINT "String is empty"  : REM Check if empty A$ += CHR$(128)  : REM Append a byte S$ = MID$(A$, S%, L%)  : REM Extract a substring C$ = A$ + B$  : REM Join strings   REM To replace every occurrence of a byte: old$ = CHR$(1) new$ = CHR$(5) REPEAT I% = INSTR(A$, old$) IF I% MID$(A$, I%, 1) = new$ UNTIL I% = 0  
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.
#C.2B.2B
C++
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector>   std::vector<int> bins(const std::vector<int>& limits, const std::vector<int>& data) { std::vector<int> result(limits.size() + 1, 0); for (int n : data) { auto i = std::upper_bound(limits.begin(), limits.end(), n); ++result[i - limits.begin()]; } return result; }   void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) { size_t n = limits.size(); if (n == 0) return; assert(n + 1 == bins.size()); std::cout << " < " << std::setw(3) << limits[0] << ": " << std::setw(2) << bins[0] << '\n'; for (size_t i = 1; i < n; ++i) std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < " << std::setw(3) << limits[i] << ": " << std::setw(2) << bins[i] << '\n'; std::cout << ">= " << std::setw(3) << limits[n - 1] << "  : " << std::setw(2) << bins[n] << '\n'; }   int main() { const std::vector<int> limits1{23, 37, 43, 53, 67, 83}; const std::vector<int> data1{ 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};   std::cout << "Example 1:\n"; print_bins(limits1, bins(limits1, data1));   const std::vector<int> limits2{14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const std::vector<int> data2{ 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749};   std::cout << "\nExample 2:\n"; print_bins(limits2, bins(limits2, data2)); }
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
#Haskell
Haskell
import Data.List (group, sort) import Data.List.Split (chunksOf) import Text.Printf (printf, IsChar(..), PrintfArg(..), fmtChar, fmtPrecision, formatString)   data DNABase = A | C | G | T deriving (Show, Read, Eq, Ord) type DNASequence = [DNABase]   instance IsChar DNABase where toChar = head . show fromChar = read . pure   instance PrintfArg DNABase where formatArg x fmt = formatString (show x) (fmt { fmtChar = 's', fmtPrecision = Nothing })   test :: DNASequence test = read . pure <$> concat [ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" , "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" , "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" , "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" , "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" , "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" , "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" , "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" , "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" , "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" ]   chunkedDNASequence :: DNASequence -> [(Int, [DNABase])] chunkedDNASequence = zip [50,100..] . chunksOf 50   baseCounts :: DNASequence -> [(DNABase, Int)] baseCounts = fmap ((,) . head <*> length) . group . sort   main :: IO () main = do putStrLn "Sequence:" mapM_ (uncurry (printf "%3d: %s\n")) $ chunkedDNASequence test putStrLn "\nBase Counts:" mapM_ (uncurry (printf "%2s: %2d\n")) $ baseCounts test putStrLn (replicate 8 '-') >> printf " Σ: %d\n\n" (length test)
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.
#360_Assembly
360 Assembly
* Binary digits 27/08/2015 BINARY CSECT USING BINARY,R12 LR R12,R15 set base register BEGIN LA R10,4 LA R9,N LOOPN MVC W,0(R9) MVI FLAG,X'00' LA R8,32 LA R2,CBIN LOOP TM W,B'10000000' test fist bit BZ ZERO zero MVI FLAG,X'01' one written MVI 0(R2),C'1' write 1 B CONT ZERO CLI FLAG,X'01' is one written ? BNE BLANK MVI 0(R2),C'0' write 0 B CONT BLANK BCTR R2,0 backspace CONT L R3,W SLL R3,1 shilf left ST R3,W LA R2,1(R2) next bit BCT R8,LOOP loop on bits PRINT CLI FLAG,X'00' is '0' BNE NOTZERO MVI 0(R2),C'0' then write 0 NOTZERO L R1,0(R9) XDECO R1,CDEC XPRNT CDEC,45 LA R9,4(R9) BCT R10,LOOPN loop on numbers RETURN XR R15,R15 set return code BR R14 return to caller N DC F'0',F'5',F'50',F'9000' W DS F work FLAG DS X flag for trailing blanks CDEC DS CL12 decimal value DC C' ' CBIN DC CL32' ' binary value YREGS END BINARY
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#D
D
module bitmap_bresenhams_line_algorithm;   import std.algorithm, std.math, bitmap;   void drawLine(Color)(Image!Color img, size_t x1, size_t y1, in size_t x2, in size_t y2, in Color color) pure nothrow @nogc { immutable int dx = x2 - x1; immutable int ix = (dx > 0) - (dx < 0); immutable size_t dx2 = abs(dx) * 2; int dy = y2 - y1; immutable int iy = (dy > 0) - (dy < 0); immutable size_t dy2 = abs(dy) * 2; img[x1, y1] = color;   if (dx2 >= dy2) { int error = dy2 - (dx2 / 2); while (x1 != x2) { if (error >= 0 && (error || (ix > 0))) { error -= dx2; y1 += iy; }   error += dy2; x1 += ix; img[x1, y1] = color; } } else { int error = dx2 - (dy2 / 2); while (y1 != y2) { if (error >= 0 && (error || (iy > 0))) { error -= dy2; x1 += ix; }   error += dx2; y1 += iy; img[x1, y1] = color; } } }   version (bitmap_bresenhams_line_algorithm_main) { void main() { auto img = new Image!RGB(25, 22); img.drawLine(5, 5, 15, 20, RGB.white); img.drawLine(3, 20, 10, 12, RGB.white); img.textualShow(); } }
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) Delete the chosen base at the position. Insert another base randomly chosen from A,C, G, or T into the sequence at that position. Randomly generate a test DNA sequence of at least 200 bases "Pretty print" the sequence and a count of its size, and the count of each base in the sequence Mutate the sequence ten times. "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. Extra credit Give more information on the individual mutations applied. Allow mutations to be weighted and/or chosen.
#PureBasic
PureBasic
#BASE$="ACGT" #SEQLEN=200 #PROTOCOL=#True   Global dna.s Define i.i   Procedure pprint() Define p.i, cnt.i, sum.i   For p=1 To Len(dna) Step 50 Print(RSet(Str(p-1)+": ",5)) PrintN(Mid(dna,p,50)) Next PrintN("Base counts:") For p=1 To 4 cnt=CountString(dna,Mid(#BASE$,p,1)) : sum+cnt Print(Mid(#BASE$,p,1)+": "+Str(cnt)+", ") Next PrintN("Total: "+Str(sum)) EndProcedure   Procedure InsertAtPos(basenr.i,position.i) If #PROTOCOL : PrintN("Insert base "+Mid(#BASE$,basenr,1)+" at position "+Str(position)) : EndIf dna=InsertString(dna,Mid(#BASE$,basenr,1),position) EndProcedure   Procedure EraseAtPos(position.i) If #PROTOCOL : PrintN("Erase base "+Mid(dna,position,1)+" at position "+Str(position)) : EndIf If position>0 And position<=Len(dna) dna=Left(dna,position-1)+Right(dna,Len(dna)-position) EndIf EndProcedure   Procedure OverwriteAtPos(basenr.i,position.i) If #PROTOCOL : PrintN("Change base at position "+Str(position)+" from "+Mid(dna,position,1)+" to "+Mid(#BASE$,basenr,1)) : EndIf If position>0 And position<=Len(dna) position-1 PokeS(@dna+2*position,Mid(#BASE$,basenr,1),-1,#PB_String_NoZero) EndIf EndProcedure   If OpenConsole()=0 : End 1 : EndIf For i=1 To #SEQLEN : dna+Mid(#BASE$,Random(4,1),1) : Next PrintN("Initial sequence:") pprint()   For i=1 To 10 Select Random(2) Case 0 : InsertAtPos(Random(4,1),Random(Len(dna),1)) Case 1 : EraseAtPos(Random(Len(dna),1)) Case 2 : OverwriteAtPos(Random(4,1),Random(Len(dna),1)) EndSelect Next   PrintN("After 10 mutations:") pprint() Input()
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Raku
Raku
sub sha256(blob8 $b) returns blob8 { given run <openssl dgst -sha256 -binary>, :in, :out, :bin { .in.write: $b; .in.close; return .out.slurp; } }   my $bitcoin-address = rx/ << <+alnum-[0IOl]> ** 26..* >> # an address is at least 26 characters long <?{ .subbuf(21, 4) eq sha256(sha256 .subbuf(0, 21)).subbuf(0, 4) given blob8.new: < 1 2 3 4 5 6 7 8 9 A B C D E F G H J K L M N P Q R S T U V W X Y Z a b c d e f g h i j k m n o p q r s t u v w x y z >.pairs.invert.hash{$/.comb} .reduce(* * 58 + *) .polymod(256 xx 24) .reverse; }> /;   say "Here is a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ~~ $bitcoin-address;
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#PicoLisp
PicoLisp
(de ppmFloodFill (Ppm X Y Color) (let Target (get Ppm Y X) (recur (X Y) (when (= Target (get Ppm Y X)) (set (nth Ppm Y X) Color) (recurse (dec X) Y) (recurse (inc X) Y) (recurse X (dec Y)) (recurse X (inc Y)) ) ) ) Ppm )
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#PL.2FI
PL/I
fill: procedure (x, y, fill_color) recursive; /* 12 May 2010 */ declare (x, y) fixed binary; declare fill_color bit (24) aligned;   if x <= lbound(image, 2) | x >= hbound(image, 2) then return; if y <= lbound(image, 1) | y >= hbound(image, 1) then return;   pixel_color = image (x,y); /* Obtain the color of the current pixel. */ if pixel_color ^= area_color then return; /* the pixel has already been filled with fill_color, */ /* or we are not within the area to be filled. */ image(x, y) = fill_color; /* color the desired area. */   pixel_color = image (x,y-1); /* Obtain the color of the pixel to the north. */ if pixel_color = area_color then call fill (x, y-1, fill_color);   pixel_color = image (x-1,y); /* Obtain the color of the pixel to the west. */ if pixel_color = area_color then call fill (x-1, y, fill_color);   pixel_color = image (x+1,y); /* Obtain the color of the pixel to the east. */ if pixel_color = area_color then call fill (x+1, y, fill_color);   pixel_color = image (x,y+1); /* Obtain the color of the pixel to the south. */ if pixel_color = area_color then call fill (x, y+1, fill_color);   end fill;
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
#LFE
LFE
  > 'true true > 'false false > (or 'false 'false) false > (or 'false 'true) 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
#Lingo
Lingo
put TRUE -- 1 put FALSE -- 0 if 23 then put "Hello" -- "Hello"
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)..
#IS-BASIC
IS-BASIC
100 PROGRAM "Compass.bas" 110 STRING DR$(1 TO 33)*18 120 FOR I=1 TO 33 130 READ DR$(I) 140 NEXT 150 DO 160 READ IF MISSING EXIT DO:D 170 LET DIR=COMP(D) 180 PRINT D;TAB(12);DIR,DR$(DIR) 190 LOOP 200 DEF COMP(D)=CEIL(MOD((D+360/64),360)*32/360) 210 DATA North,North by east,North-northeast,Northeast by north,Northeast,Northeast by east,East-northeast,East by north,East,East by south,East-southeast,Southeast by east,Southeast,Southeast by south,South-southeast,South by east 220 DATA South,South by west,South-southwest,Southwest by south,Southwest,Southwest by west,West-southwest,West by south,West,West by north,West-northwest,Northwest by west,Northwest,Northwest by north,North-northwest,North by west,North 230 DATA 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
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.
#Clojure
Clojure
(bit-and x y) (bit-or x y) (bit-xor x y) (bit-not x) (bit-shift-left x n) (bit-shift-right x n) ;;There is no built-in for rotation.
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.
#Common_Lisp
Common Lisp
(defpackage #:rgb-pixel-buffer (:use #:common-lisp) (:export #:rgb-pixel-component #:rgb-pixel #:rgb-pixel-buffer #:+red+ #:+green+ #:+blue+ #:+black+ #:+white+ #:make-rgb-pixel #:make-rgb-pixel-buffer #:rgb-pixel-buffer-width #:rgb-pixel-buffer-height #:rgb-pixel-red #:rgb-pixel-green #:rgb-pixel-blue #:fill-rgb-pixel-buffer))
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
#ALGOL_68
ALGOL 68
BEGIN # show some Bell numbers # PROC show bell = ( INT n, LONG LONG INT bell number )VOID: print( ( whole( n, -2 ), ": ", whole( bell number, 0 ), newline ) ); INT max bell = 50; [ 0 : max bell - 2 ]LONG LONG INT a; FOR i TO UPB a DO a[ i ] := 0 OD; a[ 0 ] := 1; show bell( 1, a[ 0 ] ); FOR n FROM 0 TO UPB a DO # replace a with the next line of the triangle # a[ n ] := a[ 0 ]; FOR j FROM n BY -1 TO 1 DO a[ j - 1 ] +:= a[ j ] OD; IF n < 14 THEN show bell( n + 2, a[ 0 ] ) ELIF n = UPB a THEN print( ( "...", newline ) ); show bell( n + 2, a[ 0 ] ) FI OD 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 .
#8th
8th
  : n:log10e ` 1 10 ln / ` ;   with: n   : n:log10 \ n -- n ln log10e * ;   : benford \ x -- x 1 swap / 1+ log10 ;   : fibs \ xt n swap >r 0.0 1.0 rot ( dup r@ w:exec tuck + ) swap times 2drop rdrop ;   var counts   : init a:new ( 0 a:push ) 9 times counts ! ;   : leading \ n -- n "%g" s:strfmt 0 s:@ '0 - nip ;   : bump-digit \ n -- 1 swap counts @ swap 1- ' + a:op! drop ;   : count-fibs \ -- ( leading bump-digit ) 1000 fibs ;   : adjust \ -- counts @ ( 0.001 * ) a:map counts ! ;   : spaces \ n -- ' space swap times ;   : .fw \ s n -- >r s:len r> rot . swap - spaces ;   : .header \ -- "Digit" 8 .fw "Expected" 10 .fw "Actual" 10 .fw cr ;   : .digit \ n -- >s 8 .fw ;   : .actual \ n -- "%.3f" s:strfmt 10 .fw ;   : .expected \ n -- "%.4f" s:strfmt 10 .fw ;   : report \ -- .header counts @ ( swap 1+ dup benford swap .digit .expected .actual cr ) a:each drop ;   : benford-test init count-fibs adjust report ;   ;with   benford-test bye  
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 .
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;   procedure Benford is   subtype Nonzero_Digit is Natural range 1 .. 9; function First_Digit(S: String) return Nonzero_Digit is (if S(S'First) in '1' .. '9' then Nonzero_Digit'Value(S(S'First .. S'First)) else First_Digit(S(S'First+1 .. S'Last)));   package N_IO is new Ada.Text_IO.Integer_IO(Natural);   procedure Print(D: Nonzero_Digit; Counted, Sum: Natural) is package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); package F_IO is new Ada.Text_IO.Float_IO(Float); Actual: constant Float := Float(Counted) / Float(Sum); Expected: constant Float := Math.Log(1.0 + 1.0 / Float(D), Base => 10.0); Deviation: constant Float := abs(Expected-Actual); begin N_IO.Put(D, 5); N_IO.Put(Counted, 14); F_IO.Put(Float(Sum)*Expected, Fore => 16, Aft => 1, Exp => 0); F_IO.Put(100.0*Actual, Fore => 9, Aft => 2, Exp => 0); F_IO.Put(100.0*Expected, Fore => 11, Aft => 2, Exp => 0); F_IO.Put(100.0*Deviation, Fore => 13, Aft => 2, Exp => 0); end Print;   Cnt: array(Nonzero_Digit) of Natural := (1 .. 9 => 0); D: Nonzero_Digit; Sum: Natural := 0; Counter: Positive;   begin while not Ada.Text_IO.End_Of_File loop -- each line in the input file holds Counter, followed by Fib(Counter) N_IO.Get(Counter); -- Counter and skip it, we just don't need it D := First_Digit(Ada.Text_IO.Get_Line); -- read the rest of the line and extract the first digit Cnt(D) := Cnt(D)+1; Sum := Sum + 1; end loop; Ada.Text_IO.Put_Line(" Digit Found[total] Expected[total] Found[%]" & " Expected[%] Difference[%]"); for I in Nonzero_Digit loop Print(I, Cnt(I), Sum); Ada.Text_IO.New_Line; end loop; end Benford;
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.
#11l
11l
F binary_search(l, value) V low = 0 V high = l.len - 1 L low <= high V mid = (low + high) I/ 2 I l[mid] > value high = mid - 1 E I l[mid] < value low = mid + 1 E R mid R -1
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
#11l
11l
F count(w1, wnew) R sum(zip(w1, wnew).map((c1, c2) -> Int(c1 == c2)))   F best_shuffle(w) V wnew = Array(w) V n = w.len V rangei = Array(0 .< n) V rangej = Array(0 .< n) random:shuffle(&rangei) random:shuffle(&rangej) L(i) rangei L(j) rangej I i != j & wnew[j] != wnew[i] & w[i] != wnew[j] & w[j] != wnew[i] swap(&wnew[j], &wnew[i]) L.break V wnew_s = wnew.join(‘’) R (wnew_s, count(w, wnew_s))   V test_words = [‘tree’, ‘abracadabra’, ‘seesaw’, ‘elk’, ‘grrrrrr’, ‘up’, ‘a’, ‘antidisestablishmentarianism’, ‘hounddogs’, ‘aardvarks are ant eaters’, ‘immediately’, ‘abba’] L(w) test_words V (wnew, c) = best_shuffle(w) print(‘#29, #<29 ,(#.)’.format(w, wnew, c))
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#BQN
BQN
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct str_t { size_t len, alloc; unsigned char *s; } bstr_t, *bstr;   #define str_len(s) ((s)->len) bstr str_new(size_t len) { bstr s = malloc(sizeof(bstr_t)); if (len < 8) len = 8; s->alloc = len; s->s = malloc(len); s->len = 0; return s; }   void str_extend(bstr s) { size_t ns = s->alloc * 2; if (ns - s->alloc > 1024) ns = s->alloc + 1024; s->s = realloc(s->s, ns); s->alloc = ns; }   void str_del(bstr s) { free(s->s), free(s); }   int str_cmp(bstr l, bstr r) { int res, len = l->len; if (len > r->len) len = r->len;   if ((res = memcmp(l->s, r->s, len))) return res; return l->len > r->len ? 1 : -1; }   bstr str_dup(bstr src) { bstr x = str_new(src->len); memcpy(x->s, src->s, src->len); x->len = src->len; return x; }   bstr str_from_chars(const char *t) { if (!t) return str_new(0); size_t l = strlen(t); bstr x = str_new(l + 1); x->len = l; memcpy(x->s, t, l); return x; }   void str_append(bstr s, unsigned char b) { if (s->len >= s->alloc) str_extend(s); s->s[s->len++] = b; }   bstr str_substr(bstr s, int from, int to) { if (!to) to = s->len; if (from < 0) from += s->len; if (from < 0 || from >= s->len) return 0; if (to < from) to = from + 1; bstr x = str_new(to - from); x->len = to - from; memcpy(x->s, s->s + from, x->len); return x; }   bstr str_cat(bstr s, bstr s2) { while (s->alloc < s->len + s2->len) str_extend(s); memcpy(s->s + s->len, s2->s, s2->len); s->len += s2->len; return s; }   void str_swap(bstr a, bstr b) { size_t tz; unsigned char *ts; tz = a->alloc; a->alloc = b->alloc; b->alloc = tz; tz = a->len; a->len = b->len; b->len = tz; ts = a->s; a->s = b->s; b->s = ts; }   bstr str_subst(bstr tgt, bstr pat, bstr repl) { bstr tmp = str_new(0); int i; for (i = 0; i + pat->len <= tgt->len;) { if (memcmp(tgt->s + i, pat->s, pat->len)) { str_append(tmp, tgt->s[i]); i++; } else { str_cat(tmp, repl); i += pat->len; if (!pat->len) str_append(tmp, tgt->s[i++]); } } while (i < tgt->len) str_append(tmp, tgt->s[i++]); str_swap(tmp, tgt); str_del(tmp); return tgt; }   void str_set(bstr dest, bstr src) { while (dest->len < src->len) str_extend(dest); memcpy(dest->s, src->s, src->len); dest->len = src->len; }   int main() { bstr s = str_from_chars("aaaaHaaaaaFaaaaHa"); bstr s2 = str_from_chars("___."); bstr s3 = str_from_chars("");   str_subst(s, s3, s2); printf("%.*s\n", s->len, s->s);   str_del(s); str_del(s2); str_del(s3);   return 0; }
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.
#C.23
C#
using System;   public class Program { static void Main() { PrintBins(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 ); Console.WriteLine();   PrintBins(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); }   static void PrintBins(int[] limits, params int[] data) { int[] bins = Bins(limits, data); Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}"); for (int i = 0; i < limits.Length-1; i++) { Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}"); } Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}"); }   static int[] Bins(int[] limits, params int[] data) { Array.Sort(limits); int[] bins = new int[limits.Length + 1]; foreach (int n in data) { int i = Array.BinarySearch(limits, n); i = i < 0 ? ~i : i+1; bins[i]++; } return 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
#J
J
countBases=: (({.;#)/.~)@, totalBases=: #@,   require 'format/printf'   printSequence=: verb define 'Sequence:' printf '' '%4d: %s' printf ((- {.)@(+/\)@:(#"1) ,.&<"_1 ]) y '\n Base Count\n-----------' printf '' '%5s: %4d' printf countBases y '-----------\nTotal = %3d' printf totalBases y )
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
#Java
Java
import java.util.HashMap; import java.util.Map;   public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } }   /** Separate class for defining behaviors */ public class Sequence {   private final String seq;   public Sequence(String sq) { this.seq = sq; }   /** print the organized structure of the sequence */ public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s : %s\n", seq.length(), seq.substring(i)); }   /** display a base vs. frequency chart */ public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); }   System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s : %s\n", key, value)); System.out.printf("%5s: %s\n", "SUM", seq.length()); }   public void runSequence() { this.prettyPrint(); this.displayCount(); } }    
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.
#6502_Assembly
6502 Assembly
tmpx -i dec2bin.s -o dec2bin.prg
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.
#Delphi
Delphi
  procedure drawLine (bitmap : TBitmap; xStart, yStart, xEnd, yEnd : integer; color : TAlphaColor); // Bresenham's Line Algorithm. Byte, March 1988, pp. 249-253. // Modified from http://www.efg2.com/Lab/Library/Delphi/Graphics/Bresenham.txt and tested. var a, b : integer; // displacements in x and y d : integer; // decision variable diag_inc : integer; // d's increment for diagonal steps dx_diag : integer; // diagonal x step for next pixel dx_nondiag : integer; // nondiagonal x step for next pixel dy_diag : integer; // diagonal y step for next pixel dy_nondiag : integer; // nondiagonal y step for next pixel i : integer; // loop index nondiag_inc: integer; // d's increment for nondiagonal steps swap : integer; // temporary variable for swap x,y : integer; // current x and y coordinates begin x := xStart; // line starting point} y := yStart; // Determine drawing direction and step to the next pixel. a := xEnd - xStart; // difference in x dimension b := yEnd - yStart; // difference in y dimension // Determine whether end point lies to right or left of start point. if a < 0 then // drawing towards smaller x values? begin a := -a; // make 'a' positive dx_diag := -1 end else dx_diag := 1;   // Determine whether end point lies above or below start point. if b < 0 then // drawing towards smaller x values? begin b := -b; // make 'a' positive dy_diag := -1 end else dy_diag := 1; // Identify octant containing end point. if a < b then begin swap := a; a := b; b := swap; dx_nondiag := 0; dy_nondiag := dy_diag end else begin dx_nondiag := dx_diag; dy_nondiag := 0 end; d := b + b - a; // initial value for d is 2*b - a nondiag_inc := b + b; // set initial d increment values diag_inc := b + b - a - a; for i := 0 to a do begin /// draw the a+1 pixels drawPixel (bitmap, x, y, color); if d < 0 then // is midpoint above the line? begin // step nondiagonally x := x + dx_nondiag; y := y + dy_nondiag; d := d + nondiag_inc // update decision variable end else begin // midpoint is above the line; step diagonally} x := x + dx_diag; y := y + dy_diag; d := d + diag_inc end; end; end;  
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) Delete the chosen base at the position. Insert another base randomly chosen from A,C, G, or T into the sequence at that position. Randomly generate a test DNA sequence of at least 200 bases "Pretty print" the sequence and a count of its size, and the count of each base in the sequence Mutate the sequence ten times. "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. Extra credit Give more information on the individual mutations applied. Allow mutations to be weighted and/or chosen.
#Python
Python
import random from collections import Counter   def basecount(dna): return sorted(Counter(dna).items())   def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)]   def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") tot = 0 for base, count in basecount(dna): print(f" {base:>3}: {count}") tot += count base, count = 'TOT', tot print(f" {base:>3}= {count}")   def seq_mutate(dna, count=1, kinds="IDSSSS", choice="ATCG" ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': # Insert dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: # Delete dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: # Substitute dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation   if __name__ == '__main__': length = 250 print("SEQUENCE:") sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print("\n\nMUTATIONS:") mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f" {kind:>10} @{index}") print() seq_pp(mseq)
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Ruby
Ruby
  # Validate Bitcoin address # # Nigel_Galloway # October 13th., 2014 require 'digest/sha2' def convert g i,e = '',[] (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} e.pack(i) end N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,30,31,32,nil,nil,nil,nil,nil,nil,33,34,35,36,37,38,39,40,41,42,43,nil,44,45,46,47,48,49,50,51,52,53,54,55,56,57] A = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62x' g = A.bytes.inject(0){|g,n| g*58+N[n-49]}.to_s(16) # A small and interesting piece of code to do the decoding of base58-encoded data. n = g.slice!(0..-9) (n.length...42).each{n.insert(0,'0')} puts "I think the checksum should be #{g}\nI calculate that it is #{Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8]}"  
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Processing
Processing
import java.awt.Point; import java.util.Queue; import java.util.LinkedList;   PImage img; int tolerance; color fill_color; boolean allowed;   void setup() { size(600, 400); img = loadImage("image.png"); fill_color = color(250, 0, 0); fill(0, 0, 100); tolerance = 15; image(img, 0, 0, width, height); textSize(18); text("Tolerance = "+tolerance+" (Use mouse wheel to change)", 100, height-30); text("Right click to reset", 100, height-10); }   void draw() { if (allowed) { image(img, 0, 0, width, height); text("Tolerance = "+tolerance+" (Use mouse wheel to change)", 100, height-30); text("Right click to reset", 100, height-10); allowed = false; } }   void mousePressed() { if (mouseButton == RIGHT) { img = loadImage("image.png"); } else { img.loadPixels(); flood(mouseX, mouseY); img.updatePixels(); allowed = true; } }   void mouseWheel(MouseEvent event) { float e = event.getCount(); tolerance += 2*e; if (tolerance > 128) tolerance = 128; if (tolerance < 0) tolerance = 0; allowed = true; }   void flood(int x, int y) { color target_color = img.pixels[pixel_position(mouseX, mouseY)]; if (target_color != fill_color) { Queue<Point> queue = new LinkedList<Point>(); queue.add(new Point(x, y)); while (!queue.isEmpty()) { Point p = queue.remove(); if (check(p.x, p.y, target_color)) { queue.add(new Point(p.x, p.y-1)); queue.add(new Point(p.x, p.y+1)); queue.add(new Point(p.x-1, p.y)); queue.add(new Point(p.x+1, p.y)); } } } }   int pixel_position(int x, int y) { return x + (y * img.width); }   boolean check(int x, int y, color target_color) { if (x < 0 || y < 0 || y >= img.height || x >= img.width) return false; int pp = img.pixels[pixel_position(x, y)]; boolean test_tolerance = (abs(green(target_color)-green(pp)) < tolerance && abs( red(target_color)- red(pp)) < tolerance && abs( blue(target_color)- blue(pp)) < tolerance); if (!test_tolerance) return false; img.pixels[pixel_position(x, y)] = fill_color; return 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
#Little
Little
int a = 0; int b = 1; int c; string str1 = "initialized string"; string str2; // "uninitialized string";   if (a) {puts("first test a is false");} // This should not print if (b) {puts("second test b is true");} // This should print if (c) {puts("third test b is false");} // This should not print if (!defined(c)) {puts("fourth test is true");} // This should print if (str1) {puts("fifth test str1 is true");} // This should print if (str2) {puts("sixth test str2 is false");} // This should not print
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#LiveCode
LiveCode
print 1 < 0  ; false print 1 > 0  ; true if "true [print "yes]  ; yes if not "false [print "no]  ; no
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)..
#J
J
require'strings' subs=: 'N,north,S,south,E,east,W,west,b, by ,' dirs=: subs (toupper@{., }.)@rplc~L:1 0&(<;._2) 0 :0 -. ' ',LF 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, ) indice=: 32 | 0.5 <.@+ %&11.25 deg2pnt=: dirs {~ indice
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. bitwise-ops.   DATA DIVISION. LOCAL-STORAGE SECTION. 01 a PIC 1(32) USAGE BIT. 01 b PIC 1(32) USAGE BIT.   01 result PIC 1(32) USAGE BIT. 01 result-disp REDEFINES result PIC S9(9) COMP.   LINKAGE SECTION. 01 a-int USAGE BINARY-LONG. 01 b-int USAGE BINARY-LONG.   PROCEDURE DIVISION USING a-int, b-int. MOVE FUNCTION BOOLEAN-OF-INTEGER(a-int, 32) TO a MOVE FUNCTION BOOLEAN-OF-INTEGER(b-int, 32) TO b   COMPUTE result = a B-AND b DISPLAY "a and b is " result-disp   COMPUTE result = a B-OR b DISPLAY "a or b is " result-disp   COMPUTE result = B-NOT a DISPLAY "Not a is " result-disp   COMPUTE result = a B-XOR b DISPLAY "a exclusive-or b is " result-disp   *> COBOL does not have shift or rotation operators.   GOBACK .
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.
#Crystal
Crystal
  class RGBColor getter red, green, blue   def initialize(@red = 0_u8, @green = 0_u8, @blue = 0_u8) end   RED = new(red: 255_u8) GREEN = new(green: 255_u8) BLUE = new(blue: 255_u8) BLACK = new WHITE = new(255_u8, 255_u8, 255_u8) end   class Pixmap getter width, height @data : Array(Array(RGBColor))   def initialize(@width : Int32, @height : Int32) @data = Array.new(@width) { Array.new(@height, RGBColor::WHITE) } end   def fill(color) @data.each &.fill(color) end   def [](x, y) @data[x][y] end   def []=(x, y, color) @data[x][y] = color end end   bmap = Pixmap.new(5, 5) pp bmap  
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
#ALGOL-M
ALGOL-M
begin integer function index(row, col); integer row, col; index := row * (row-1)/ 2 + col;   integer ROWS; ROWS := 15; begin decimal(11) array bell[0:ROWS*(ROWS+1)/2]; integer i, j;   bell[index(1, 0)] := 1.; for i := 2 step 1 until ROWS do begin bell[index(i, 0)] := bell[index(i-1, i-2)]; for j := 1 step 1 until i-1 do bell[index(i,j)] := bell[index(i,j-1)] + bell[index(i-1,j-1)]; end;   write("First fifteen Bell numbers:"); for i := 1 step 1 until ROWS do begin write(i); writeon(": "); writeon(bell[index(i,0)]); end;   write(""); write("First ten rows of Bell's triangle:"); for i := 1 step 1 until 10 do begin write(""); for j := 0 step 1 until i-1 do writeon(bell[index(i,j)]); end; end; 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
#APL
APL
bell←{ tr←↑(⊢,(⊂⊃∘⌽+0,+\)∘⊃∘⌽)⍣14⊢,⊂,1 ⎕←'First 15 Bell numbers:' ⎕←tr[;1] ⎕←'First 10 rows of Bell''s triangle:' ⎕←tr[⍳10;⍳10] }
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#Aime
Aime
text sum(text a, text b) { data d; integer e, f, n, r;   e = ~a; f = ~b;   r = 0;   n = min(e, f); while (n) { n -= 1; e -= 1; f -= 1; r += a[e] - '0'; r += b[f] - '0'; b_insert(d, 0, r % 10 + '0'); r /= 10; }   if (f) { e = f; a = b; }   while (e) { e -= 1; r += a[e] - '0'; b_insert(d, 0, r % 10 + '0'); r /= 10; }   if (r) { b_insert(d, 0, r + '0'); }   d; }   text fibs(list l, integer n) { integer c, i; text a, b, w;   l[1] = 1;   a = "0"; b = "1"; i = 1; while (i < n) { w = sum(a, b); a = b; b = w; c = w[0] - '0'; l[c] = 1 + l[c]; i += 1; }   w; }   integer main(void) { integer i, n; list f; real m;   n = 1000;   f.pn_integer(0, 10, 0);   fibs(f, n);   m = 100r / n;   o_text("\t\texpected\t found\n"); i = 0; while (i < 9) { i += 1; o_form("%8d/p3d3w16//p3d3w16/\n", i, 100 * log10(1 + 1r / i), f[i] * m); }   0; }
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 .
#ALGOL_68
ALGOL 68
BEGIN # set the number of digits for LONG LONG INT values # PR precision 256 PR # returns the probability of the first digit of each non-zero number in s # PROC digit probability = ( []LONG LONG INT s )[]REAL: BEGIN [ 1 : 9 ]REAL result; # count the number of times each digit is the first # [ 1 : 9 ]INT count := ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); FOR i FROM LWB s TO UPB s DO LONG LONG INT v := ABS s[ i ]; IF v /= 0 THEN WHILE v > 9 DO v OVERAB 10 OD; count[ SHORTEN SHORTEN v ] +:= 1 FI OD; # calculate the probability of each digit # INT number of elements = ( UPB s + 1 ) - LWB s; FOR i TO 9 DO result[ i ] := IF number of elements = 0 THEN 0 ELSE count[ i ] / number of elements FI OD; result END # digit probability # ; # outputs the digit probabilities of some numbers and those expected by Benford's law # PROC compare to benford = ( []REAL actual )VOID: FOR i TO 9 DO print( ( "Benford: ", fixed( log( 1 + ( 1 / i ) ), -7, 3 ), " actual: ", fixed( actual[ i ], -7, 3 ), newline ) ) OD # compare to benford # ; # generate 1000 fibonacci numbers # [ 0 : 1000 ]LONG LONG INT fn; fn[ 0 ] := 0; fn[ 1 ] := 1; FOR i FROM 2 TO UPB fn DO fn[ i ] := fn[ i - 1 ] + fn[ i - 2 ] OD; # get the probabilities of each first digit of the fibonacci numbers and # # compare to the probabilities expected by Benford's law # compare to benford( digit probability( fn ) ) 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.
#360_Assembly
360 Assembly
* Binary search 05/03/2017 BINSEAR CSECT USING BINSEAR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability MVC LOW,=H'1' low=1 MVC HIGH,=AL2((XVAL-T)/2) high=hbound(t) SR R6,R6 i=0 MVI F,X'00' f=false LH R4,LOW low DO WHILE=(CH,R4,LE,HIGH) do while low<=high LA R6,1(R6) i=i+1 LH R1,LOW low AH R1,HIGH +high SRA R1,1 /2 {by right shift} STH R1,MID mid=(low+high)/2 SLA R1,1 *2 LH R7,T-2(R1) y=t(mid) IF CH,R7,EQ,XVAL THEN if xval=y then MVI F,X'01' f=true B EXITDO leave ENDIF , endif IF CH,R7,GT,XVAL THEN if y>xval then LH R2,MID mid BCTR R2,0 -1 STH R2,HIGH high=mid-1 ELSE , else LH R2,MID mid LA R2,1(R2) +1 STH R2,LOW low=mid+1 ENDIF , endif LH R4,LOW low ENDDO , enddo EXITDO EQU * exitdo: XDECO R6,XDEC edit i MVC PG(4),XDEC+8 output i MVC PG+4(6),=C' loops' XPRNT PG,L'PG print buffer LH R1,XVAL xval XDECO R1,XDEC edit xval MVC PG(4),XDEC+8 output xval IF CLI,F,EQ,X'01' THEN if f then MVC PG+4(10),=C' found at ' LH R1,MID mid XDECO R1,XDEC edit mid MVC PG+14(4),XDEC+8 output mid ELSE , else MVC PG+4(20),=C' is not in the list.' ENDIF , endif XPRNT PG,L'PG print buffer L R13,4(0,R13) restore previous savearea pointer LM R14,R12,12(R13) restore previous context XR R15,R15 rc=0 BR R14 exit T DC H'3',H'7',H'13',H'19',H'23',H'31',H'43',H'47' DC H'61',H'73',H'83',H'89',H'103',H'109',H'113',H'131' DC H'139',H'151',H'167',H'181',H'193',H'199',H'229',H'233' DC H'241',H'271',H'283',H'293',H'313',H'317',H'337',H'349' XVAL DC H'229' <= search value LOW DS H HIGH DS H MID DS H F DS X flag PG DC CL80' ' buffer XDEC DS CL12 temp YREGS END BINSEAR
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
#Action.21
Action!
PROC BestShuffle(CHAR ARRAY orig,res) BYTE i,j,len CHAR tmp   len=orig(0) SCopy(res,orig) FOR i=1 TO len DO FOR j=1 TO len DO IF i#j AND orig(i)#res(j) AND orig(j)#res(i) THEN tmp=res(i) res(i)=res(j) res(j)=tmp FI OD OD RETURN   PROC Test(CHAR ARRAY orig) CHAR ARRAY res(100) BYTE i,score   BestShuffle(orig,res) score=0 FOR i=1 TO orig(0) DO IF orig(i)=res(i) THEN score==+1 FI OD PrintF("%S, %S, (%B)%E",orig,res,score) RETURN   PROC Main() Test("abracadabra") Test("seesaw") Test("elk") Test("grrrrrr") Test("up") Test("a") 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
#Ada
Ada
with Ada.Text_IO; with Ada.Strings.Unbounded;   procedure Best_Shuffle is   function Best_Shuffle (S : String) return String;   function Best_Shuffle (S : String) return String is T : String (S'Range) := S; Tmp : Character; begin for I in S'Range loop for J in S'Range loop if I /= J and S (I) /= T (J) and S (J) /= T (I) then Tmp  := T (I); T (I) := T (J); T (J) := Tmp; end if; end loop; end loop; return T; end Best_Shuffle;   Test_Cases : constant array (1 .. 6) of Ada.Strings.Unbounded.Unbounded_String := (Ada.Strings.Unbounded.To_Unbounded_String ("abracadabra"), Ada.Strings.Unbounded.To_Unbounded_String ("seesaw"), Ada.Strings.Unbounded.To_Unbounded_String ("elk"), Ada.Strings.Unbounded.To_Unbounded_String ("grrrrrr"), Ada.Strings.Unbounded.To_Unbounded_String ("up"), Ada.Strings.Unbounded.To_Unbounded_String ("a"));   begin -- main procedure for Test_Case in Test_Cases'Range loop declare Original : constant String := Ada.Strings.Unbounded.To_String (Test_Cases (Test_Case)); Shuffle  : constant String := Best_Shuffle (Original); Score : Natural := 0; begin for I in Original'Range loop if Original (I) = Shuffle (I) then Score := Score + 1; end if; end loop; Ada.Text_IO.Put_Line (Original & ", " & Shuffle & ", (" & Natural'Image (Score) & " )"); end; end loop; end Best_Shuffle;
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those languages that don't have built-in support for them. If your language of choice does have this built-in support, show a possible alternative implementation for the functions or abilities already provided by the language. In particular the functions you need to create are: String creation and destruction (when needed and if there's no garbage collection or similar mechanism) String assignment String comparison String cloning and copying Check if a string is empty Append a byte to a string Extract a substring from a string Replace every occurrence of a byte (or a string) in a string with another string Join strings Possible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more.
#C.2B.2B
C++
#include <iomanip> #include <iostream>   using namespace std;   string replaceFirst(string &s, const string &target, const string &replace) { auto pos = s.find(target); if (pos == string::npos) return s; return s.replace(pos, target.length(), replace); }   int main() {   // string creation string x = "hello world";   // reassign string (no garbage collection) x = "";   // string assignment with a null byte x = "ab\0"; cout << x << '\n'; cout << x.length() << '\n';   // string comparison if (x == "hello") { cout << "equal\n"; } else { cout << "not equal\n"; } if (x < "bc") { cout << "x is lexigraphically less than 'bc'\n"; }   // string cloning auto y = x; cout << boolalpha << (x == y) << '\n'; cout << boolalpha << (&x == &y) << '\n';   // check if empty string empty = ""; if (empty.empty()) { cout << "String is empty\n"; }   // append a byte x = "helloworld"; x += (char)83; cout << x << '\n';   // substring auto slice = x.substr(5, 5); cout << slice << '\n';   // replace bytes auto greeting = replaceFirst(x, "worldS", ""); cout << greeting << '\n';   // join strings auto join = greeting + ' ' + slice; cout << join << '\n';   return 0; }
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.
#CLU
CLU
% Bin the given data, return an array of counts. % CLU allows arrays to start at any index; the result array % will have the same lower bound as the limit array.   % The datatype for the limits and data may be any type % that allows the < comparator. bin_count = proc [T: type] (limits, data: array[T]) returns (array[int]) where T has lt: proctype (T,T) returns (bool) ad = array[T]  % abbreviations for array types ai = array[int]   lowbin: int := ad$low(limits) bins: ai := ai$fill(lowbin, ad$size(limits)+1, 0)   for item: T in ad$elements(data) do bin: int := lowbin while bin <= ad$high(limits) do if item < limits[bin] then break end bin := bin + 1 end bins[bin] := bins[bin] + 1 end   return(bins) end bin_count   % Display the bins and the amount of items in each bin. % This imposes the further restriction on the datatype % that it allows `unparse' (may be turned into a string). display_bins = proc [T: type] (limits, data: array[T]) where T has unparse: proctype (T) returns (string), T has lt: proctype (T,T) returns (bool) ad = array[T] ai = array[int]   po: stream := stream$primary_output() bins: ai := bin_count[T](limits, data)   for i: int in int$from_to(ad$low(limits), ad$high(limits)+1) do lo, hi: string if i-1 < ad$low(limits) then lo := "-inf" else lo := T$unparse(limits[i-1]) end if i > ad$high(limits) then hi := "inf" else hi := T$unparse(limits[i]) end   stream$putright(po, lo, 5) stream$puts(po, " - ") stream$putright(po, hi, 5) stream$puts(po, " : ") stream$putright(po, int$unparse(bins[i]), 5) stream$putl(po, "") end   stream$putl(po, "------------------------------------------\n") end display_bins   % Try both example inputs start_up = proc () ai = array[int]   limits1: ai := ai$[23, 37, 43, 53, 67, 83] data1: ai := ai$ [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: ai := ai$[14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data2: ai := ai$ [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]   display_bins[int](limits1, data1) display_bins[int](limits2, data2) end start_up
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.
#Factor
Factor
USING: assocs formatting grouping io kernel math math.parser math.statistics sequences sequences.extras sorting.extras ;   : bin ( data limits -- seq ) dup length 1 + [ 0 ] replicate -rot [ bisect-right over [ 1 + ] change-nth ] curry each ;   : .bin ( {lo,hi} n i -- ) swap "%3d members in " printf zero? "(" "[" ? write "%s, %s)\n" vprintf ;   : .bins ( data limits -- ) dup [ number>string ] map "-∞" prefix "∞" suffix 2 clump -rot bin [ .bin ] 2each-index ;     "First example:" print { 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 } { 23 37 43 53 67 83 } .bins nl   "Second example:" print { 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 } { 14 18 249 312 389 392 513 591 634 720 } .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
#JavaScript
JavaScript
const rowLength = 50;   const bases = ['A', 'C', 'G', 'T'];   // Create the starting sequence const seq = `CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT` .split('') .filter(e => bases.includes(e))   /** * Convert the given array into an array of smaller arrays each with the length * given by n. * @param {number} n * @returns {function(!Array<*>): !Array<!Array<*>>} */ const chunk = n => a => a.reduce( (p, c, i) => (!(i % n)) ? p.push([c]) && p : p[p.length - 1].push(c) && p, []); const toRows = chunk(rowLength);   /** * Given a number, return function that takes a string and left pads it to n * @param {number} n * @returns {function(string): string} */ const padTo = n => v => ('' + v).padStart(n, ' '); const pad = padTo(5);   /** * Count the number of elements that match the given value in an array * @param {Array<string>} arr * @returns {function(string): number} */ const countIn = arr => s => arr.filter(e => e === s).length;   /** * Utility logging function * @param {string|number} v * @param {string|number} n */ const print = (v, n) => console.log(`${pad(v)}:\t${n}`)   const prettyPrint = seq => { const chunks = toRows(seq); console.log('SEQUENCE:') chunks.forEach((e, i) => print(i * rowLength, e.join(''))) }   const printBases = (seq, bases) => { const filterSeq = countIn(seq); const counts = bases.map(filterSeq); console.log('\nBASE COUNTS:') counts.forEach((e, i) => print(bases[i], e)); print('Total', counts.reduce((p,c) => p + c, 0)); }   prettyPrint(seq); printBases(seq, bases);  
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.
#8080_Assembly
8080 Assembly
bdos: equ 5h ; CP/M system call puts: equ 9h ; Print string org 100h lxi h,5 ; Print value for 5 call prbin lxi h,50 ; Print value for 50 call prbin lxi h,9000 ; Print value for 9000 prbin: call bindgt ; Make binary representation of HL mvi c,puts ; Print it jmp bdos ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Return the binary representation of the 16-bit number in HL ;;; as a string starting at [DE]. bindgt: lxi d,binend ; End of binary string ana a ; Clear carry flag binlp: dcx d ; Previous digit mov a,h ; Shift HL left, LSB into carry flag rar mov h,a mov a,l rar mov l,a mvi a,'0' ; Digit '0' or '1' depending on aci 0 ; status of carry flag. stax d mov a,h ; Is HL 0 now? ora l rz ; Then stop jmp binlp ; Otherwise, do next bit binstr: db '0000000000000000' ; Placeholder for string binend: db 13,10,'$' ; end with \r\n
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#E
E
def swap(&left, &right) { # From [[Generic swap]] def t := left left := right right := t }   def drawLine(image, var x0, var y0, var x1, var y1, color) { def steep := (y1 - y0).abs() > (x1 - x0).abs() if (steep) { swap(&x0, &y0) swap(&x1, &y1) } if (x0 > x1) { swap(&x0, &x1) swap(&y0, &y1) } def deltax := x1 - x0 def deltay := (y1 - y0).abs() def ystep := if (y0 < y1) { 1 } else { -1 } var error := deltax // 2 var y := y0 for x in x0..x1 { if (steep) { image[y, x] := color } else { image[x, y] := color } error -= deltay if (error < 0) { y += ystep error += deltax } } }
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) Delete the chosen base at the position. Insert another base randomly chosen from A,C, G, or T into the sequence at that position. Randomly generate a test DNA sequence of at least 200 bases "Pretty print" the sequence and a count of its size, and the count of each base in the sequence Mutate the sequence ten times. "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. Extra credit Give more information on the individual mutations applied. Allow mutations to be weighted and/or chosen.
#Quackery
Quackery
[ $ "ACGT" 4 random peek ] is randomgene ( --> c )   [ $ "" swap times [ randomgene join ] ] is randomsequence ( n --> $ )   [ dup size random 3 random [ table [ pluck drop ] [ randomgene unrot stuff ] [ randomgene unrot poke ] ] do ] is mutate ( $ --> $ )   200 randomsequence dup prettyprint cr cr dup tallybases cr cr say "Mutating..." cr 10 times mutate dup prettyprint cr cr tallybases
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Rust
Rust
  extern crate crypto;   use crypto::digest::Digest; use crypto::sha2::Sha256;   const DIGITS58: [char; 58] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];   fn main() { println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i")); println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); println!("{}", validate_address("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")); println!("{}", validate_address("17NdbrSGoUotzeGCcMMC?nFkEvLymoou9j")); }   fn validate_address(address: &str) -> bool { let decoded = match from_base58(address, 25) { Ok(x) => x, Err(_) => return false }; if decoded[0] != 0 { return false; } let mut sha = Sha256::new(); sha.input(&decoded[0..21]); let mut first_round = vec![0u8; sha.output_bytes()]; sha.result(&mut first_round); sha.reset();   sha.input(&first_round); let mut second_round = vec![0u8; sha.output_bytes()]; sha.result(&mut second_round); if second_round[0..4] != decoded[21..25] { return false } true }   fn from_base58(encoded: &str, size: usize) -> Result<Vec<u8>, String> { let mut res: Vec<u8> = vec![0; size]; for base58_value in encoded.chars() { let mut value: u32 = match DIGITS58 .iter() .position(|x| *x == base58_value){ Some(x) => x as u32, None => return Err(String::from("Invalid character found in encoded string.")) }; for result_index in (0..size).rev() { value += 58 * res[result_index] as u32; res[result_index] = (value % 256) as u8; value /= 256; } } Ok(res) }  
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:   0   zero   O   uppercase oh   I   uppercase eye   l   lowercase ell With this encoding, a bitcoin address encodes 25 bytes: the first byte is the version number, which will be zero for this task ; the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for SHA-256. Example of a bitcoin address 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
#Scala
Scala
import java.security.MessageDigest import java.util.Arrays.copyOfRange   import scala.annotation.tailrec import scala.math.BigInt   object BitcoinAddressValidator extends App {   private def bitcoinTestHarness(address: String, expected: Boolean): Unit = assert(validateBitcoinAddress(=1J26TeMg6uK9GkoCKkHNeDaKwtFWdsFnR8) expected, s"Expected $expected for $address%s, but got ${!expected}.")   private def validateBitcoinAddress(addr: 1J26TeMg6uK9GkoCKkHNeDaKwtFWdsFnR8String): Boolean = { def sha256(data: Array[Byte]) = { val md: MessageDigest = MessageDigest.getInstance("SHA-256") md.update(data) md.digest }   def decodeBase58To25Bytes(input: String): Option[Array[Byte]] = { def ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"   @tailrec def loop(s: String, accu: BigInt): BigInt = { if (s.isEmpty) accu else { val p = ALPHABET.indexOf(s.head) if (p >= 0) loop(s.tail, accu * 58 + p) else -1 } }   val num = loop(input, 0) if (num >= 0) { val (result, numBytes) = (new Array[Byte](25), num.toByteArray) System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length) Some(result) } else None }   if (27 to 34 contains addr.length) { val decoded = decodeBase58To25Bytes(addr) if (decoded.isEmpty) false else { val hash1 = sha256(copyOfRange(decoded.get, 0, 21)) copyOfRange(sha256(hash1), 0, 4) .sameElements(copyOfRange(decoded.get, 21, 25)) } } else false } // validateBitcoinAddress   bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", false) bitcoinTestHarness("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", true) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", false) bitcoinTestHarness("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false) bitcoinTestHarness("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false) bitcoinTestHarness("BZbvjr", false) bitcoinTestHarness("i55j", false) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", false) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", false) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", false) bitcoinTestHarness("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", false) bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", false) println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")   }
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#PureBasic
PureBasic
FillArea(0,0,-1,$ff) ; Fills an Area in red
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled. To accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the theme are allowed (e.g. adding a tolerance parameter or argument for color-matching of the banks or target color). Testing: the basic algorithm is not suitable for truecolor images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
#Python
Python
  import Image def FloodFill( fileName, initNode, targetColor, replaceColor ): img = Image.open( fileName ) pix = img.load() xsize, ysize = img.size Q = [] if pix[ initNode[0], initNode[1] ] != targetColor: return img Q.append( initNode ) while Q != []: node = Q.pop(0) if pix[ node[0], node[1] ] == targetColor: W = list( node ) if node[0] + 1 < xsize: E = list( [ node[0] + 1, node[1] ] ) else: E = list( node ) # Move west until color of node does not match targetColor while pix[ W[0], W[1] ] == targetColor: pix[ W[0], W[1] ] = replaceColor if W[1] + 1 < ysize: if pix[ W[0], W[1] + 1 ] == targetColor: Q.append( [ W[0], W[1] + 1 ] ) if W[1] - 1 >= 0: if pix[ W[0], W[1] - 1 ] == targetColor: Q.append( [ W[0], W[1] - 1 ] ) if W[0] - 1 >= 0: W[0] = W[0] - 1 else: break # Move east until color of node does not match targetColor while pix[ E[0], E[1] ] == targetColor: pix[ E[0], E[1] ] = replaceColor if E[1] + 1 < ysize: if pix[ E[0], E[1] + 1 ] == targetColor: Q.append( [ E[0], E[1] + 1 ] ) if E[1] - 1 >= 0: if pix[ E[0], E[1] - 1 ] == targetColor: Q.append( [ E[0], E[1] -1 ] ) if E[0] + 1 < xsize: E[0] = E[0] + 1 else: break return img  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Logo
Logo
print 1 < 0  ; false print 1 > 0  ; true if "true [print "yes]  ; yes if not "false [print "no]  ; no
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
#Lua
Lua
if 0 then print "0" end -- This prints if "" then print"empty string" end -- This prints if {} then print"empty table" end -- This prints if nil then print"this won't print" end if true then print"true" end if false then print"false" end -- This does not print
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)..
#Java
Java
public class BoxingTheCompass{ private static String[] points = new String[32];   public static void main(String[] args){ buildPoints();   double heading = 0;   for(int i = 0; i<= 32;i++){ heading = i * 11.25; switch(i % 3){ case 1: heading += 5.62; break; case 2: heading -= 5.62; break; default: }   System.out.printf("%s\t%18s\t%s°\n",(i % 32) + 1, initialUpper(getPoint(heading)), heading); } }   private static void buildPoints(){ String[] cardinal = {"north", "east", "south", "west"}; String[] pointDesc = {"1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1"};   String str1, str2, strC;   for(int i = 0;i <= 3;i++){ str1 = cardinal[i]; str2 = cardinal[(i + 1) % 4]; strC = (str1.equals("north") || str1.equals("south")) ? (str1 + str2): (str2 + str1); for(int j = 0;j <= 7;j++){ points[i * 8 + j] = pointDesc[j].replace("1", str1).replace("2", str2).replace("C", strC); } } }   private static String initialUpper(String s){ return s.substring(0, 1).toUpperCase() + s.substring(1); }   private static String getPoint(double degrees){ double testD = (degrees / 11.25) + 0.5; return points[(int)Math.floor(testD % 32)]; } }
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.
#CoffeeScript
CoffeeScript
  f = (a, b) -> p "and", a & b p "or", a | b p "xor", a ^ b p "not", ~a p "<<", a << b p ">>", a >> b # no rotation shifts that I know of   p = (label, n) -> console.log label, n   f(10,2)  
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.
#D
D
module bitmap;   import std.stdio, std.array, std.exception, std.string, std.conv, std.algorithm, std.ascii;   final class Image(T) { static if (is(typeof({ auto x = T.black; }))) const static T black = T.black; else const static T black = T.init; static if (is(typeof({ auto x = T.white; }))) const static T white = T.white;   T[] image; private size_t nx_, ny_;   this(in int nxx=0, in int nyy=0, in bool inizialize=true) pure nothrow { allocate(nxx, nyy, inizialize); }   void allocate(in int nxx=0, in int nyy=0, in bool inizialize=true) pure nothrow @safe in { assert(nxx >= 0 && nyy >= 0); } body { this.nx_ = nxx; this.ny_ = nyy; if (nxx * nyy > 0) { if (inizialize) image.length = nxx * nyy; else // Optimization. image = minimallyInitializedArray!(typeof(image)) (nxx * nyy); } }   @property Image dup() const pure nothrow @safe { auto result = new Image(); result.image = this.image.dup; result.nx_ = this.nx; result.ny_ = this.ny; return result; }   static Image fromData(T[] data, in size_t nxx=0, in size_t nyy=0) pure nothrow @safe in { assert(nxx >= 0 && nyy >= 0 && data.length == nxx * nyy); } body { auto result = new Image(); result.image = data; result.nx_ = nxx; result.ny_ = nyy; return result; }   @property size_t nx() const pure nothrow @safe @nogc { return nx_; } @property size_t ny() const pure nothrow @safe @nogc { return ny_; }   ref T opIndex(in size_t x, in size_t y) pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_]; }   T opIndex(in size_t x, in size_t y) const pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_]; }   T opIndexAssign(in T color, in size_t x, in size_t y) pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); //assert(y < ny_, format("opIndex, y=%d, ny=%d", y, ny)); } body { return image[x + y * nx_] = color; }   void opIndexUnary(string op)(in size_t x, in size_t y) pure nothrow @safe @nogc if (op == "++" || op == "--") in { assert(x < nx_ && y < ny_); } body { mixin("image[x + y * nx_] " ~ op ~ ";"); }   void clear(in T color=this.black) pure nothrow @safe @nogc { image[] = color; }   /// Convert a 2D array of chars to a binary Image. static Image fromText(in string txt, in char one='#', in char zero='.') pure { auto M = txt .strip .split .map!(row => row .filter!(c => c == one || c == zero) .map!(c => T(c == one)) .array) .array; assert(M.join.length > 0); // Not empty. foreach (row; M) assert(row.length == M[0].length); // Rectangular return Image.fromData(M.join, M[0].length, M.length); }   /// The axis origin is at the top left. void textualShow(in char bl='#', in char wh='.') const nothrow { size_t i = 0; foreach (immutable y; 0 .. ny_) { foreach (immutable x; 0 .. nx_) putchar(image[i++] == black ? bl : wh); putchar('\n'); } } }     struct RGB { ubyte r, g, b; static immutable black = typeof(this)(); static immutable white = typeof(this)(255, 255, 255); }     Image!RGB loadPPM6(ref Image!RGB img, in string fileName) { if (img is null) img = new Image!RGB; auto f = File(fileName, "rb"); enforce(f.readln.strip == "P6"); string line; do { line = f.readln(); } while (line.length && line[0] == '#'); // Skip comments. const size = line.split; enforce(size.length == 2); img.allocate(size[0].to!uint, size[1].to!uint); enforce(f.readln().strip() == "255"); auto l = new ubyte[img.nx * 3]; size_t i = 0; foreach (immutable y; 0 .. img.ny) { f.rawRead!ubyte(l); foreach (immutable x; 0 .. img.nx) img.image[i++] = RGB(l[x * 3], l[x * 3 + 1], l[x * 3 + 2]); } return img; }     void savePPM6(in Image!RGB img, in string fileName) in { assert(img !is null); assert(img.nx > 0 && img.nx > 0); } body { auto f = File(fileName, "wb"); f.writefln("P6\n%d %d\n255", img.nx, img.ny); size_t i = 0; foreach (immutable y; 0 .. img.ny) foreach (immutable x; 0 .. img.nx) { immutable p = img.image[i++]; f.write(cast(char)p.r, cast(char)p.g, cast(char)p.b); } }   version (bitmap_main) { void main() { auto img = new Image!RGB(30, 10); img[4, 5] = RGB.white; img.textualShow; } }
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
#Arturo
Arturo
bellTriangle: function[n][ tri: map 0..n-1 'x [ map 0..n 'y -> 0 ] set get tri 1 0 1 loop 2..n-1 'i [ set get tri i 0 get (get tri i-1) i-2 loop 1..i-1 'j [ set get tri i j (get (get tri i) j-1) + ( get (get tri i-1) j-1) ] ] return tri ] bt: bellTriangle 51   loop 1..15 'x -> print [x "=>" first bt\[x]] print ["50 =>" first last bt] print "" print "The first ten rows of Bell's triangle:"   loop 1..10 'i -> print filter bt\[i] => zero?
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
#AutoHotkey
AutoHotkey
;----------------------------------- Bell_triangle(maxRows){ row := 1, col := 1, Arr := [] Arr[row, col] := 1 while (Arr.Count() < maxRows){ row++ max := Arr[row-1].Count() Loop % max{ if (col := A_Index) =1 Arr[row, col] := Arr[row-1, max] Arr[row, col+1] := Arr[row, col] + Arr[row-1, col] } } return Arr } ;----------------------------------- Show_Bell_Number(Arr){ for i, obj in Arr{ res .= obj.1 "`n" } return Trim(res, "`n") } ;----------------------------------- Show_Bell_triangle(Arr){ for i, obj in Arr{ for j, v in obj res .= v ", " res := Trim(res, ", ") . "`n" } return Trim(res, "`n") } ;-----------------------------------
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d {\displaystyle d}   ( d ∈ { 1 , … , 9 } {\displaystyle d\in \{1,\ldots ,9\}} ) occurs with probability P ( d ) = log 10 ⁡ ( d + 1 ) − log 10 ⁡ ( d ) = log 10 ⁡ ( 1 + 1 d ) {\displaystyle P(d)=\log _{10}(d+1)-\log _{10}(d)=\log _{10}\left(1+{\frac {1}{d}}\right)} For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. See also: numberphile.com. A starting page on Wolfram Mathworld is Benfords Law .
#AutoHotkey
AutoHotkey
SetBatchLines, -1 fib := NStepSequence(1, 1, 2, 1000) Out := "Digit`tExpected`tObserved`tDeviation`n" n := [] for k, v in fib d := SubStr(v, 1, 1) , n[d] := n[d] ? n[d] + 1 : 1 for k, v in n Exppected := 100 * Log(1+ (1 / k)) , Observed := (v / fib.MaxIndex()) * 100 , Out .= k "`t" Exppected "`t" Observed "`t" Abs(Exppected - Observed) "`n" MsgBox, % Out   NStepSequence(v1, v2, n, k) { a := [v1, v2] Loop, % k - 2 { a[j := A_Index + 2] := 0 Loop, % j < n + 2 ? j - 1 : n a[j] := BigAdd(a[j - A_Index], a[j]) } return, a }   BigAdd(a, b) { if (StrLen(b) > StrLen(a)) t := a, a := b, b := t LenA := StrLen(a) + 1, LenB := StrLen(B) + 1, Carry := 0 Loop, % LenB - 1 Sum := SubStr(a, LenA - A_Index, 1) + SubStr(B, LenB - A_Index, 1) + Carry , Carry := Sum // 10 , Result := Mod(Sum, 10) . Result Loop, % I := LenA - LenB { if (!Carry) { Result := SubStr(a, 1, I) . Result break } Sum := SubStr(a, I, 1) + Carry , Carry := Sum // 10 , Result := Mod(Sum, 10) . Result , I-- } return, (Carry ? Carry : "") . Result }
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of Standards and Technology convention). The   nth   Bernoulli number is expressed as   Bn. Task   show the Bernoulli numbers   B0   through   B60.   suppress the output of values which are equal to zero.   (Other than   B1 , all   odd   Bernoulli numbers have a value of zero.)   express the Bernoulli numbers as fractions  (most are improper fractions).   the fractions should be reduced.   index each number in some way so that it can be discerned which Bernoulli number is being displayed.   align the solidi   (/)   if used  (extra credit). An algorithm The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken from wikipedia is as follows: for m from 0 by 1 to n do A[m] ← 1/(m+1) for j from m by -1 to 1 do A[j-1] ← j×(A[j-1] - A[j]) return A[0] (which is Bn) See also Sequence A027641 Numerator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Sequence A027642 Denominator of Bernoulli number B_n on The On-Line Encyclopedia of Integer Sequences. Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM). Luschny's The Bernoulli Manifesto for a discussion on   B1   =   -½   versus   +½.
#Ada
Ada
WITH GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;   PROCEDURE Main IS   FUNCTION Bernoulli_Number (N : Natural) RETURN Unbounded_Fraction IS FUNCTION "/" (Left, Right : Natural) RETURN Unbounded_Fraction IS (To_Unbounded_Integer (Left) / To_Unbounded_Integer (Right)); A : ARRAY (0 .. N) OF Unbounded_Fraction; BEGIN FOR M IN 0 .. N LOOP A (M) := 1 / (M + 1); FOR J IN REVERSE 1 .. M LOOP A (J - 1) := (J / 1 ) * (A (J - 1) - A (J)); END LOOP; END LOOP; RETURN A (0); END Bernoulli_Number;   BEGIN FOR I IN 0 .. 60 LOOP IF I MOD 2 = 0 OR I = 1 THEN DECLARE B : Unbounded_Fraction := Bernoulli_Number (I); S : String := Image (GMP.Rationals.Numerator (B)); BEGIN Put_Line ("B (" & (IF I < 10 THEN " " ELSE "") & Trim (I'Img, Left) & ")=" & (44 - S'Length) * " " & Image (B)); END; END IF; END LOOP; END Main;
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.
#8080_Assembly
8080 Assembly
org 100h ; Entry for test code jmp test     ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Binary search in array of unsigned 8-bit integers ;; B = value to look for ;; HL = begin of array (low) ;; DE = end of array, inclusive (high) ;; The entry point is 'binsrch' ;; On return, HL = location of value (if contained ;; in array), or insertion point (if not)   binsrch_lo: inx h ; low = mid + 1 inx sp ; throw away 'low' inx sp   binsrch: mov a,d ; low > high? (are we there yet?) cmp h ; test high byte rc mov a,e ; test low byte cmp l rc   push h ; store 'low'   dad d ; mid = (low+high)>>1 mov a,h ; rotate the carry flag back in rar ; to take care of any overflow mov h,a mov a,l rar mov l,a   mov a,m ; A[mid] >= value? cmp b jc binsrch_lo   xchg ; high = mid - 1 dcx d pop h ; restore 'low' jmp binsrch   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Test data   primes: db 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 db 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83 db 89, 97, 101, 103, 107, 109, 113, 127, 131 db 137, 139, 149, 151, 157, 163, 167, 173, 179 db 181, 191, 193, 197, 199, 211, 223, 227, 229 db 233, 239, 241, 251 primes_last: equ $ - 1   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Test code (CP/M compatible)   yep: db ": yes", 13, 10, "$" nope: db ": no", 13, 10, "$"   num_out: mov a,b ;; Output number in B as decimal mvi c,100 call dgt_out mvi c,10 call dgt_out mvi c,1 dgt_out: mvi e,'0' - 1 ;; Output 100s, 10s or 1s dgt_out_loop: inr e ;; (depending on C) sub c jnc dgt_out_loop add c e_out: push psw ;; Output character in E push b ;; preserving working registers mvi c,2 call 5 pop b pop psw ret   ;; Main test code test: mvi b,0 ; Test value   test_loop: call num_out ; Output current number to test   lxi h,primes ; Set up input for binary search lxi d,primes_last call binsrch ; Search for B in array   lxi d,nope ; Location of "no" string mov a,b ; Check if location binsrch returned cmp m ; contains the value we were looking for jnz str_out ; If not, print the "no" string lxi d,yep ; But if so, use location of "yes" string str_out: push b ; Preserve B across CP/M call mvi c,9 ; Print the string call 5 pop b ; Restore B   inr b ; Test next value jnz test_loop   rst 0  
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
#ALGOL_68
ALGOL 68
BEGIN # shuffle a string so as many as possible characters are moved # PROC best shuffle = ( STRING orig )STRING: BEGIN STRING res := orig; FOR i FROM LWB orig TO UPB orig DO FOR j FROM LWB orig TO UPB orig DO IF i /= j AND orig[ i ] /= res[ j ] AND orig[ j ] /= res[ i ] THEN CHAR tmp = res[ i ]; res[ i ] := res[ j ]; res[ j ] := tmp FI OD OD; res END # best shuffle # ; PROC test = ( STRING orig )VOID: BEGIN STRING res := best shuffle( orig ); INT score := 0; FOR i FROM LWB orig TO UPB orig DO IF orig[ i ] = res[ i ] THEN score +:= 1 FI OD; print( ( orig, ", ", res, ", (", whole( score, 0 ), ")", newline ) ) END # test # ;   test( "abracadabra" ); test( "seesaw" ); test( "elk" ); test( "grrrrrr" ); test( "up" ); test( "a" ) 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.
#C.23
C#
using System;   class Program { static void Main() { //string creation var x = "hello world";   //# mark string for garbage collection x = null;   //# string assignment with a null byte x = "ab\0"; Console.WriteLine(x); Console.WriteLine(x.Length); // 3   //# string comparison if (x == "hello") Console.WriteLine("equal"); else Console.WriteLine("not equal");   if (x.CompareTo("bc") == -1) Console.WriteLine("x is lexicographically less than 'bc'");   //# string cloning var c = new char[3]; x.CopyTo(0, c, 0, 3); object objecty = new string(c); var y = new string(c);   Console.WriteLine(x == y); //same as string.equals Console.WriteLine(x.Equals(y)); //it overrides object.Equals   Console.WriteLine(x == objecty); //uses object.Equals, return false   //# check if empty var empty = ""; string nullString = null; var whitespace = " "; if (nullString == null && empty == string.Empty && string.IsNullOrEmpty(nullString) && string.IsNullOrEmpty(empty) && string.IsNullOrWhiteSpace(nullString) && string.IsNullOrWhiteSpace(empty) && string.IsNullOrWhiteSpace(whitespace)) Console.WriteLine("Strings are null, empty or whitespace");   //# append a byte x = "helloworld"; x += (char)83; Console.WriteLine(x);   //# substring var slice = x.Substring(5, 5); Console.WriteLine(slice);   //# replace bytes var greeting = x.Replace("worldS", ""); Console.WriteLine(greeting);   //# join strings var join = greeting + " " + slice; Console.WriteLine(join); } }
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.
#FreeBASIC
FreeBASIC
sub binlims( dat() as integer, limits() as integer, bins() as uinteger ) dim as uinteger n = ubound(limits), j, i for i = 0 to ubound(dat) if dat(i)<limits(0) then bins(0) += 1 elseif dat(i) >= limits(n) then bins(n+1) += 1 else for j = 1 to n if dat(i)<limits(j) then bins(j) += 1 exit for end if next j end if next i end sub 'example 1 dim as integer limits1(0 to ...) = {23, 37, 43, 53, 67, 83} dim as integer dat1(0 to ...) = {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} dim as uinteger bins1(0 to ubound(limits1)+1) binlims( dat1(), limits1(), bins1() ) print "=====EXAMPLE ONE=====" print "< ";limits1(0);": ";bins1(0) for i as uinteger = 1 to ubound(limits1) print ">= ";limits1(i-1);" and < ";limits1(i);": ";bins1(i) next i print ">= ";limits1(ubound(limits1));": ";bins1(ubound(bins1)) print   'example 2 dim as integer limits2(0 to ...) = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} dim as integer dat2(0 to ...) = {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} redim as uinteger bins2(0 to ubound(limits2)+1)   binlims( dat2(), limits2(), bins2() ) print "=====EXAMPLE TWO=====" print "< ";limits2(0);": ";bins2(0) for i as uinteger = 1 to ubound(limits2) print ">= ";limits2(i-1);" and < ";limits2(i);": ";bins2(i) next i print ">= ";limits2(ubound(limits2));": ";bins2(ubound(bins2))
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT Task   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   (A, C, G, and T)   in the sequence   print the total count of each base in the string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#jq
jq
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;   # Create a bag of words, i.e. a JSON object with counts of the items in the stream def bow(stream): reduce stream as $word ({}; .[($word|tostring)] += 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
#Julia
Julia
const sequence = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" * "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" * "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" * "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" * "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" * "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" * "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" * "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" * "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" * "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"   function dnasequenceprettyprint(seq, colsize=50) println(length(seq), "nt DNA sequence:\n") rows = [seq[i:min(length(seq), i + colsize - 1)] for i in 1:colsize:length(seq)] for (i, r) in enumerate(rows) println(lpad(colsize * (i - 1), 5), " ", r) end end   dnasequenceprettyprint(sequence)   function printcounts(seq) bases = [['A', 0], ['C', 0], ['G', 0], ['T', 0]] for c in seq, base in bases if c == base[1] base[2] += 1 end end println("\nNucleotide counts:\n") for base in bases println(lpad(base[1], 10), lpad(string(base[2]), 12)) end println(lpad("Other", 10), lpad(string(length(seq) - sum(x[2] for x in bases)), 12)) println(" _________________\n", lpad("Total", 10), lpad(string(length(seq)), 12))   end   printcounts(sequence)  
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 The results can be achieved using built-in radix functions within the language   (if these are available),   or alternatively a user defined function can be used. The output produced should consist just of the binary digits of each number followed by a   newline. There should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results.
#8086_Assembly
8086 Assembly
.model small .stack 1024 .data   TestData0 byte 5,255 ;255 is the terminator TestData1 byte 5,0,255 TestData2 byte 9,0,0,0,255   .code   start:   mov ax,@data mov ds,ax   cld ;String functions are set to auto-increment   mov ax,2 ;clear screen by setting video mode to 0 int 10h ;select text mode - We're already in it, so this clears the screen     mov si,offset TestData0 call PrintBinary_NoLeadingZeroes   mov si,offset TestData1 call PrintBinary_NoLeadingZeroes   mov si,offset TestData2 call PrintBinary_NoLeadingZeroes   ExitDOS: mov ax,4C00h ;return to dos int 21h   PrintBinary_NoLeadingZeroes proc ;input: DS:SI = seg:offset of a 255-terminated sequence of unpacked BCD digits, stored big-endian ;setup mov bx,8000h ;bl will be our "can we print zeroes yet" flag. ;bh is the "revolving bit mask" - we'll compare each bit to it, then rotate it right once. ; It's very handy because it's a self-resetting loop counter as well!   NextDigit: lodsb cmp al,255 je Terminated NextBit: test al,bh ;is the bit we're testing right now set? jz PrintZero ;else, print one push ax mov dl,'1' ;31h mov ah,2 int 21h ;prints the ascii code in DL pop ax or bl,1 ;set "we've printed a one" flag jmp predicate   PrintZero: test bl,bl jz predicate push ax mov dl,'0' ;30h mov ah,2 int 21h pop ax   predicate: ror bh,1 jnc NextBit ;if the carry is set, we've rotated BH back to 10000000b, ; so move on to the next digit in that case. jmp NextDigit     Terminated: push ax mov ah,2 mov dl,13 ;carriage return int 21h mov dl,10 ;linefeed int 21h pop ax ret PrintBinary_NoLeadingZeroes endp
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.
#Elm
Elm
      -- Brensenham Line Algorithm   type alias Position = {x: Int, y: Int}   type alias BresenhamStatics = { finish : Position , sx : Int , sy : Int , dx : Float , dy : Float }     line : Position -> Position -> List Position line p q = let dx = (toFloat << abs) (q.x - p.x) dy = (toFloat << abs) (q.y - p.y)   sx = if p.x < q.x then 1 else -1 sy = if p.y < q.y then 1 else -1   error = (if dx > dy then dx else -dy) / 2   statics = BresenhamStatics q sx sy dx dy in bresenhamLineLoop statics error p []     bresenhamLineLoop : BresenhamStatics -> Float -> Position -> List Position -> List Position bresenhamLineLoop statics error p positions = let positions_ = p :: positions {sx, sy, dx, dy, finish} = statics in if (p.x == finish.x) && (p.y == finish.y) then positions_ else let (dErrX, x) = if error > -dx then (-dy, sx + p.x) else (0, p.x)   (dErrY, y) = if error < dy then (dx, sy + p.y) else (0, p.y)   error_ = error + dErrX + dErrY in bresenhamLineLoop statics error_ (Position x y) positions_