task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#D
D
import std.array : uninitializedArray; import std.bigint; import std.stdio : writeln, writefln;   auto bellTriangle(int n) { auto tri = uninitializedArray!(BigInt[][])(n); foreach (i; 0..n) { tri[i] = uninitializedArray!(BigInt[])(i); tri[i][] = BigInt(0); } tri[1][0] = 1; foreach (i...
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 freque...
#CoffeeScript
CoffeeScript
fibgen = () -> a = 1; b = 0 return () -> ([a, b] = [b, a+b])[1]   leading = (x) -> x.toString().charCodeAt(0) - 0x30   f = fibgen()   benford = (0 for i in [1..9]) benford[leading(f()) - 1] += 1 for i in [1..1000]   log10 = (x) -> Math.log(x) * Math.LOG10E   actual = benford.map (x) -> x * 0.001 expecte...
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 S...
#C.2B.2B
C++
/** * Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 * Apple LLVM version 9.1.0 (clang-902.0.39.1) * Target: x86_64-apple-darwin17.5.0 * Thread model: posix */   #include <boost/multiprecision/cpp_int.hpp> // 1024bit precision #include <boost/rationa...
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 p...
#ALGOL_68
ALGOL 68
BEGIN MODE ELEMENT = STRING;   # Iterative: # PROC iterative binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: ( INT out, low := LWB hay stack, high := UPB hay stack; WHILE low < high DO INT mid := (low+high) OVER 2; IF hay stack[mid] > needle THEN high := mid-1 E...
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...
#BBC_BASIC
BBC BASIC
a$ = "abracadabra" : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "seesaw"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "elk"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,b$) a$ = "grrrrrr"  : b$ = FNshuffle(a$) : PRINT a$ " -> " b$ FNsame(a$,...
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...
#Bracmat
Bracmat
  ( shuffle = m car cdr todo a z count string .  !arg:(@(?:%?car ?cdr).?todo) & !Count:?count & ( @( !todo  :  ?a (%@:~!car:?m) ( ?z & shuffle$(!cdr.str$(!a !z))  : (<!count:...
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 la...
#Erlang
Erlang
-module(binary_string). -compile([export_all]).   %% Erlang has very easy handling of binary strings. Using %% binary/bitstring syntax the various task features will be %% demonstrated.     %% Erlang has GC so destruction is not shown. test() -> Binary = <<0,1,1,2,3,5,8,13>>, % binaries can be created directly ...
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] ...
#Lua
Lua
  function binner(limits, data) local bins = setmetatable({}, {__index=function() return 0 end}) local n, flr = #limits+1, math.floor for _, x in ipairs(data) do local lo, hi = 1, n while lo < hi do local mid = flr((lo + hi) / 2) if not limits[mid] or x < limits[mid] then hi=mid else lo=mid+1...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Perl
Perl
use strict; use warnings; use feature 'say';   my %cnt; my $total = 0;   while ($_ = <DATA>) { chomp; printf "%4d: %s\n", $total+1, s/(.{10})/$1 /gr; $total += length; $cnt{$_}++ for split // }   say "\nTotal bases: $total"; say "$_: " . ($cnt{$_}//0) for <A C G T>;   __DATA__ CGTAAAAAATTACAACGTCCTTTGGC...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Phix
Phix
constant dna = substitute(""" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTC...
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 ...
#Ada
Ada
with ada.text_io; use ada.text_io; procedure binary is bit : array (0..1) of character := ('0','1');   function bin_image (n : Natural) return string is (if n < 2 then (1 => bit (n)) else bin_image (n / 2) & bit (n mod 2));   test_values : array (1..3) of Natural := (5,50,9000); begin for test of test_valu...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Factor
Factor
USING: accessors arrays kernel locals math math.functions math.ranges math.vectors rosettacode.raster.display rosettacode.raster.storage sequences ui.gadgets ; IN: rosettacode.raster.line   :: line-points ( pt1 pt2 -- points ) pt1 first2 :> y0! :> x0! pt2 first2 :> y1! :> x1! y1 y0 - abs x1 x0 - abs > :> st...
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 vall...
#Standard_ML
Standard ML
(* For simplicity, we're going to fill black-and-white images. Nothing * fundamental would change if we used more colors. *) datatype color = Black | White (* Represent an image as a 2D mutable array of pixels, since flood-fill * is naturally an imperative algorithm. *) type image = color array array   (* Helper func...
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 vall...
#Tcl
Tcl
package require Tcl 8.5 package require Tk package require struct::queue   proc floodFill {img colour point} { set new [colour2rgb $colour] set old [getPixel $img $point] struct::queue Q Q put $point while {[Q size] > 0} { set p [Q get] if {[getPixel $img $p] eq $old} { s...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nanoquery
Nanoquery
a = true b = false   if a println "a is true" else if b println "b is true" end
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Neko
Neko
/* boolean values */ $print(true, "\n"); $print(false, "\n");   if 0 { $print("literal 0 tests true\n"); } else { $print("literal 0 tests false\n"); }   if 1 { $print("literal 1 tests true\n"); } else { $print("literal 1 tests false\n"); }   if $istrue(0) { $print("$istrue(0) tests true\n"); } else { $print...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nemerle
Nemerle
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]   loop b_ = 0 for bval.length select case bval[b_] when isTrue then say bval[b_] 'is true' when isFalse then say bval[b_] 'is false' otherwise say bval[b_]...
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...
#Lasso
Lasso
define pointsarray() => { local(points = array) loop(-from=0,-to=32) => { local(heading = loop_count * 11.25) if(loop_count % 3 == 1) => { #heading += 5.62 else(loop_count % 3 == 2) #heading -= 5.62 } #points->insert(#heading) } return #points } define compassShort => array( 'N','Nbe','N-ne','Nebn'...
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 |...
#ECL
ECL
  BitwiseOperations(INTEGER A, INTEGER B) := FUNCTION BitAND := A & B; BitOR  := A | B; BitXOR := A ^ B; BitNOT := BNOT A; BitSL  := A << B; BitSR  := A >> B; DS  := DATASET([{A,B,'Bitwise AND:',BitAND}, {A,B,'Bitwise OR:',BitOR}, {A,B,'Bitwise XOR',BitXOR}, {A,B,'Bitwise 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 pixe...
#Euphoria
Euphoria
-- Some color constants: constant black = #000000, white = #FFFFFF, red = #FF0000, green = #00FF00, blue = #0000FF   -- Create new image filled with some color function new_image(integer width, integer height, atom fill_color) return repeat(repeat(fill_color,height),width) end function   -- U...
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...
#Delphi
Delphi
  program BellNumbers;   // For Rosetta Code. // Delphi console application to display the Bell numbers B_0, ..., B_25. // Uses signed 64-bit integers, the largest integer type available in Delphi.   {$APPTYPE CONSOLE}   uses SysUtils; // only for the display   const MAX_INDEX = 25; // maximum index within the limits...
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 freque...
#Common_Lisp
Common Lisp
(defun calculate-distribution (numbers) "Return the frequency distribution of the most significant nonzero digits in the given list of numbers. The first element of the list is the frequency for digit 1, the second for digit 2, and so on."   (defun nonzero-digit-p (c) "Check whether the character is a n...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Clojure
Clojure
    ns test-project-intellij.core (:gen-class))   (defn a-t [n] " Used Akiyama-Tanigawa algorithm with a single loop rather than double nested loop " " Clojure does fractional arithmetic automatically so that part is easy " (loop [m 0 j m A (vec (map #(/ 1 %) (range 1 (+ n 2))))] ; Prefil A(m)...
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 p...
#ALGOL_W
ALGOL W
begin % binary search %  % recursive binary search, left most insertion point % integer procedure binarySearchLR ( integer array A ( * )  ; integer value find, Low, high ) ; if high < low then low else begin inte...
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...
#C
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <limits.h>   #define DEBUG   void best_shuffle(const char* txt, char* result) { const size_t len = strlen(txt); if (len == 0) return;   #ifdef DEBUG // txt and result must have the same length assert(len == s...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Factor
Factor
"Hello, byte-array!" utf8 encode .
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Forth
Forth
\ Rosetta Code Binary Strings Demo in Forth \ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html   \ String words created in this code: \ STR< STR> STR= COMPARESTR SUBSTR STRPAD CLEARSTR \ ="" =" STRING: MAXLEN REPLACE-CHAR COPYSTR WRI...
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] ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
limits = {23, 37, 43, 53, 67, 83}; data = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; limits = {{-\[Infinity]}~Join~limits~Join~{\[Infinity]}}; BinCounts[da...
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] ...
#Nim
Nim
import algorithm, strformat   func binIt(limits, data: openArray[int]): seq[Natural] = result.setLen(limits.len + 1) for d in data: inc result[limits.upperBound(d)]   proc binPrint(limits: openArray[int]; bins: seq[Natural]) = echo &" < {limits[0]:3} := {bins[0]:3}" for i in 1..limits.high: ech...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Picat
Picat
main => dna(DNA, ChunkSize), Count = 0, println("Sequence:"), Map = new_map(['A'=0,'C'=0,'G'=0,'T'=0]), foreach(Chunk in DNA.chunks_of(ChunkSize)) printf("%4d: %s\n", Count, Chunk), Count := Count + Chunk.len, foreach(C in Chunk) Map.put(C,Map.get(C)+1) end end, println("\nBase count...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#PicoLisp
PicoLisp
(let (S (chop "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\ CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\ AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\ GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\ CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\ TCAGTCCCAATG...
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 ...
#Aime
Aime
o_xinteger(2, 0); o_byte('\n'); o_xinteger(2, 5); o_byte('\n'); o_xinteger(2, 50); o_byte('\n'); o_form("/x2/\n", 9000);
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Bresenham") ' Set form caption FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 200, 235) CENTER(M...
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 vall...
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window import "input" for Keyboard   class Bitmap { construct new(name, size) { Window.title = name Window.resize(size, size) Canvas.resize(size, size) size = size / 2 _bmp = ImageData.create(name, size, size) ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   bval = [1, 0, 5, 'a', 1 == 1, 1 \= 1, isTrue, isFalse]   loop b_ = 0 for bval.length select case bval[b_] when isTrue then say bval[b_] 'is true' when isFalse then say bval[b_] 'is false' otherwise say bval[b_]...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Nim
Nim
if true: echo "yes" if false: echo "no"   # Other objects never represent true or false: if 2: echo "compile error"
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Liberty_BASIC
Liberty BASIC
dim point$( 32)   for i =1 to 32 read d$: point$( i) =d$ next i   for i = 0 to 32 heading = i *11.25 if ( i mod 3) =1 then heading = heading +5.62 else if ( i mod 3) =2 then heading = heading -5.62 end if ind = i mod 32 +1 print ind, compasspoint$( heading), heading next i   ...
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 |...
#Elena
Elena
import extensions;   extension testOp { bitwiseTest(y) { console.printLine(self," and ",y," = ",self.and(y)); console.printLine(self," or ",y," = ",self.or(y)); console.printLine(self," xor ",y," = ",self.xor(y)); console.printLine("not ",self," = ",self.Inverted); consol...
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 pixe...
#F.23
F#
  //pure functional version ... changing a pixel color provides a new Bitmap type Color = {red: byte; green: byte; blue: byte} type Point = {x:uint32; y:uint32} type Bitmap = {color: Color array; maxX: uint32; maxY: uint32}   let colorBlack = {red = (byte) 0; green = (byte) 0; blue = (byte) 0} let emptyBitmap = {color...
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...
#Elixir
Elixir
  defmodule Bell do def triangle(), do: Stream.iterate([1], fn l -> bell_row l, [List.last l] end) def numbers(), do: triangle() |> Stream.map(&List.first/1)   defp bell_row([], r), do: Enum.reverse r defp bell_row([a|a_s], r = [r0|_]), do: bell_row(a_s, [a + r0|r]) end   :io.format "The first 15 bell n...
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...
#F.23
F#
  // Generate bell triangle. Nigel Galloway: July 6th., 2019 let bell=Seq.unfold(fun g->Some(g,List.scan(+) (List.last g) g))[1I]  
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Crystal
Crystal
require "big"   EXPECTED = (1..9).map{ |d| Math.log10(1 + 1.0 / d) }   def fib(n) a, b = 0.to_big_i, 1.to_big_i (0...n).map { ret, a, b = a, b, a + b; ret } end   # powers of 3 as a test sequence def power_of_threes(n) (0...n).map { |k| 3.to_big_i ** k } end   def heads(s) s.map { |a| a.to_s[0].to_i } end   def...
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 S...
#Common_Lisp
Common Lisp
(defun bernouilli (n) (loop with a = (make-array (list (1+ n))) for m from 0 to n do (setf (aref a m) (/ 1 (+ m 1))) (loop for j from m downto 1 do (setf (aref a (- j 1)) (* j (- (aref a j) (aref a (- j 1)))))) finally (return (aref a 0))))   ;;Print outputs to st...
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 p...
#APL
APL
binsrch←{ ⎕IO(⍺{ ⍝ first lower bound is start of array ⍵<⍺:⍬ ⍝ if high < low, we didn't find it mid←⌊(⍺+⍵)÷2 ⍝ calculate mid point ⍺⍺[mid]>⍵⍵:⍺∇mid-1 ⍝ if too high, search from ⍺ to mid-1 ⍺⍺[mid]<⍵⍵:(mid+1)∇⍵ ⍝ if too low, sea...
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...
#C.23
C#
ShuffledString[] array = {"cat", "dog", "mouse"};
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <algorithm>   using namespace std;   template <class S> class BestShuffle { public: BestShuffle() : rd(), g(rd()) {}   S operator()(const S& s1) { S s2 = s1; shuffle(s2.begin(), s2.end(), g); for (unsigned i = 0; i < s2.length(); i++) ...
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 la...
#FreeBASIC
FreeBASIC
  Dim As String cad, cad2 'creación de cadenas cad = "¡Hola Mundo!"   'destrucción de cadenas: no es necesario debido a la recolección de basura cad = ""   'clonación/copia de cadena cad2 = cad   'comparación de cadenas If cad = cad2 Then Print "Las cadenas son iguales"   'comprobar si está vacío If cad = "" Then Print...
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] ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   NSArray<NSNumber *> *bins(NSArray<NSNumber *> *limits, NSArray<NSNumber *> *data) { NSMutableArray<NSNumber *> *result = [[NSMutableArray alloc] initWithCapacity:[limits count] + 1]; for (NSInteger i = 0; i <= [limits count]; i++) { [result addObject:@0]; } for (NSNumber ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#PureBasic
PureBasic
dna$ = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCT...
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 ...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   printf(( $g" => "2r3d l$, 5, BIN 5, $g" => "2r6d l$, 50, BIN 50, $g" => "2r14d l$, 9000, BIN 9000 ));   # or coerce to an array of BOOL # print(( 5, " => ", []BOOL(BIN 5)[bits width-3+1:], new line, 50, " => ", []BOOL(BIN 50)[bits width-6+1:], new line, 9000, " => ", []BOO...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Forth
Forth
defer steep \ noop or swap defer ystep \ 1+ or 1-   : line ( x0 y0 x1 y1 color bmp -- ) { color bmp } rot swap ( x0 x1 y0 y1 ) 2dup - abs >r 2over - abs r> < if ['] swap \ swap use of x and y else 2swap ['] noop then is steep ( y0 y1 x0 x1 ) 2dup > if swap 2swap swap...
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 vall...
#XPL0
XPL0
include c:\cxpl\codes;   proc Flood(X, Y, C, C0); \Fill an area of color C0 with color C int X, Y, \seed coordinate (where to start) C, C0; \color to fill with and color to replace def S=8000; \size of queue (must be an even number) int Q(S), \queue (FIFO) F, E; \fill and empty...
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 vall...
#zkl
zkl
fcn flood(pixmap, x,y, repl){ // slow! targ,h,w:=pixmap[x,y], pixmap.h,pixmap.w; stack:=List(T(x,y)); while(stack){ x,y:=stack.pop(); if((0<=y<h) and (0<=x<w)){ p:=pixmap[x,y]; if(p==targ){ pixmap[x,y]=repl; stack.append( T(x-1,y), T(x+1,y), T(x, y-1), T(x, y+1) ); } } } }
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oberon-2
Oberon-2
  VAR a,b,c: BOOLEAN; ... a := TRUE; b := FALSE; c := 1 > 2;  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Objeck
Objeck
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Object_Pascal
Object Pascal
type bool = false | true
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#LLVM
LLVM
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring.   ; Additional comments have been inserted, as well as changes made from the output produced by clang such ...
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 |...
#Elixir
Elixir
defmodule Bitwise_operation do use Bitwise   def test(a \\ 255, b \\ 170, c \\ 2) do IO.puts "Bitwise function:" IO.puts "band(#{a}, #{b}) = #{band(a, b)}" IO.puts "bor(#{a}, #{b}) = #{bor(a, b)}" IO.puts "bxor(#{a}, #{b}) = #{bxor(a, b)}" IO.puts "bnot(#{a}) = #{bnot(a)}" IO.puts "bsl(#{a},...
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 pixe...
#Factor
Factor
USING: arrays fry kernel math.matrices sequences ; IN: rosettacode.raster.storage   ! Various utilities : meach ( matrix quot -- ) [ each ] curry each ; inline : meach-index ( matrix quot -- ) [ swap 2array ] prepose [ curry each-index ] curry each-index ; inline : mmap ( matrix quot -- matrix' ) [ map ] curry...
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...
#Factor
Factor
USING: formatting io kernel math math.matrices sequences vectors ;   : next-row ( prev -- next ) [ 1 1vector ] [ dup last [ + ] accumulate swap suffix! ] if-empty ;   : aitken ( n -- seq ) V{ } clone swap [ next-row dup ] replicate nip ;   0 50 aitken col [ 15 head ] [ last ] bi "First 15 Bell numbers:\n%[%...
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...
#FreeBASIC
FreeBASIC
#define MAX 21   #macro ncp(n, p) (fact(n)/(fact(p))/(fact(n-p))) #endmacro   dim as ulongint fact(0 to MAX), bell(0 to MAX) dim as uinteger n=0, k   fact(0) = 1 for k=1 to MAX fact(k) = k*fact(k-1) next k   bell(n) = 1 print n, bell(n) for n=0 to MAX-1 for k=0 to n bell(n+1) += ncp(n, k)*bell(k) ...
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 freque...
#D
D
import std.stdio, std.range, std.math, std.conv, std.bigint;   double[2][9] benford(R)(R seq) if (isForwardRange!R && !isInfinite!R) { typeof(return) freqs = 0; uint seqLen = 0; foreach (d; seq) if (d != 0) { freqs[d.text[0] - '1'][1]++; seqLen++; }   foreach (imm...
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 S...
#Crystal
Crystal
require "big"   class Bernoulli include Iterator(Tuple(Int32, BigRational))   def initialize @a = [] of BigRational @m = 0 end   def next @a << BigRational.new(1, @m+1) @m.downto(1) { |j| @a[j-1] = j*(@a[j-1] - @a[j]) } v = @m.odd? && @m != 1 ? BigRational.new(0, 1) : @a.first return {@m...
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 p...
#AppleScript
AppleScript
on binarySearch(n, theList, l, r) repeat until (l = r) set m to (l + r) div 2 if (item m of theList < n) then set l to m + 1 else set r to m end if end repeat   if (item l of theList is n) then return l return missing value end binarySearch   on te...
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...
#Clojure
Clojure
(defn score [before after] (->> (map = before after) (filter true? ,) count))   (defn merge-vecs [init vecs] (reduce (fn [counts [index x]] (assoc counts x (conj (get counts x []) index))) init vecs))   (defn frequency "Returns a collection of indecies of distinct items" [coll] (->> (map-indexed vect...
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 la...
#Go
Go
package main   import ( "bytes" "fmt" )   // Strings in Go allow arbitrary bytes. They are implemented basically as // immutable byte slices and syntactic sugar. This program shows functions // required by the task on byte slices, thus it mostly highlights what // happens behind the syntactic sugar. The prog...
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] ...
#Perl
Perl
use strict; use warnings; no warnings 'uninitialized'; use feature 'say'; use experimental 'signatures'; use constant Inf => 1e10;   my @tests = ( { limits => [23, 37, 43, 53, 67, 83], data => [ 95,21,94,12,99,4,70,75,83,93,52,80,57, 5,53,86,65,17,92,83,71,61,54,58,47, 16, ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Python
Python
from collections import Counter   def basecount(dna): return sorted(Counter(dna).items())   def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)]   def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f"{i*n:>5}: {part}") print("\n BASECOUNT:") t...
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 ...
#ALGOL-M
ALGOL-M
begin procedure writebin(n); integer n; begin procedure inner(x); integer x; begin if x>1 then inner(x/2); writeon(if x-x/2*2=0 then "0" else "1"); end; write(""); % start new line % inner(n); end;   writebin(5); writebin(50...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Fortran
Fortran
module RCImagePrimitive use RCImageBasic   implicit none   type point integer :: x, y end type point   private :: swapcoord   contains   subroutine swapcoord(p1, p2) integer, intent(inout) :: p1, p2 integer :: t   t = p2 p2 = p1 p1 = t end subroutine swapcoord   subroutine draw_...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Objective-C
Objective-C
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#OCaml
OCaml
type bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Octave
Octave
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Logo
Logo
; List of abbreviated compass point labels make "compass_points [ N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW ]   ; List of angles to test make "test_angles [ 0.0...
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Erlang
Erlang
  -module(bitwise_operations).   -export([test/0]).   test() -> A = 255, B = 170, io:format("~p band ~p = ~p\n",[A,B,A band B]), io:format("~p bor ~p = ~p\n",[A,B,A bor B]), io:format("~p bxor ~p = ~p\n",[A,B,A bxor B]), io:format("not ~p = ~p\n",[A,bnot A]), io:format("~p bsl ~p = ~p\n",[A,B,A bsl...
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 pixe...
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_RBUTTONDOWN 516 #DEFINE WM_CLOSE 16   FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: set persistent background color DRAWWIDTH(5) ' Adjust point size FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 300, 200) CENTER(ME) SHOW(ME)   BEGIN E...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   func bellTriangle(n int) [][]*big.Int { tri := make([][]*big.Int, n) for i := 0; i < n; i++ { tri[i] = make([]*big.Int, i) for j := 0; j < i; j++ { tri[i][j] = new(big.Int) } } tri[1][0].SetUint64(1) for i := 2;...
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 freque...
#Delphi
Delphi
defmodule Benfords_law do def distribution(n), do: :math.log10( 1 + (1 / n) )   def task(total \\ 1000) do IO.puts "Digit Actual Benfords expected" fib(total) |> Enum.group_by(fn i -> hd(to_char_list(i)) end) |> Enum.map(fn {key,list} -> {key - ?0, length(list)} end) |> Enum.sort |> Enum.eac...
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 freque...
#Elixir
Elixir
defmodule Benfords_law do def distribution(n), do: :math.log10( 1 + (1 / n) )   def task(total \\ 1000) do IO.puts "Digit Actual Benfords expected" fib(total) |> Enum.group_by(fn i -> hd(to_char_list(i)) end) |> Enum.map(fn {key,list} -> {key - ?0, length(list)} end) |> Enum.sort |> Enum.eac...
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 S...
#D
D
import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational;   auto bernoulli(in uint n) pure nothrow /*@safe*/ { auto A = new Rational[n + 1]; foreach (immutable m; 0 .. n + 1) { A[m] = Rational(1, m + 1); foreach_reverse (immutable j; 1 .. m + 1) A[j - 1] = j * (A[j -...
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 p...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program binsearch.s */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /**********************...
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...
#Common_Lisp
Common Lisp
(defun count-equal-chars (string1 string2) (loop for c1 across string1 and c2 across string2 count (char= c1 c2)))   (defun shuffle (string) (let ((length (length string)) (result (copy-seq string))) (dotimes (i length result) (dotimes (j length) (when (and (/= i j) ...
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 la...
#Groovy
Groovy
import java.nio.charset.StandardCharsets   class MutableByteString { private byte[] bytes private int length   MutableByteString(byte... bytes) { setInternal(bytes) }   int length() { return length }   boolean isEmpty() { return length == 0 }   byte get(int in...
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] ...
#Phix
Phix
with javascript_semantics function bin_it(sequence limits, data) -- Bin data according to (ascending) limits. sequence bins = repeat(0,length(limits)+1) -- adds under/over range bins too for i=1 to length(data) do integer bdx = binary_search(data[i],limits) bdx = abs(bdx)+(bdx>0) bi...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Quackery
Quackery
  [ over size - space swap of swap join ] is justify ( $ n --> $ )   [ 0 swap [ dup $ "" != while cr over number$ 4 justify echo$ 5 times [ dup $ "" = iff conclude done sp 10 split swap echo$ ] dip [ 50 + ] again ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#R
R
  #Data gene1 <- "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATT...
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 ...
#APL
APL
base2←2∘⊥⍣¯1
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#FreeBASIC
FreeBASIC
' version 16-09-2015 ' compile with: fbc -s console ' OR compile with: fbc -s gui   ' Ported from the C version Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, Col As Integer = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) Dim As Integer sx = IIf(x0 < x1, 1, -1) Dim...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Oforth
Oforth
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Ol
Ol
my $x = 0.0; my $true_or_false = $x ? 'true' : 'false'; # false
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Lua
Lua
-- List of abbreviated compass point labels compass_points = { "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN", "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE", "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS", "W", "WbN", "W-NW", "NWbW", "...
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 |...
#F.23
F#
let bitwise a b = printfn "a and b: %d" (a &&& b) printfn "a or b: %d" (a ||| b) printfn "a xor b: %d" (a ^^^ b) printfn "not a: %d" (~~~a) printfn "a shl b: %d" (a <<< b) printfn "a shr b: %d" (a >>> b) // arithmetic shift printfn "a shr b: %d" ((uint32 a) >>> b) // logical shif...
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 pixe...
#Forth
Forth
hex 0000ff constant red 00ff00 constant green ff0000 constant blue decimal   1 cells constant pixel : pixels cells ;   : bdim ( bmp -- w h ) 2@ ; : bheight ( bmp -- h ) @ ; : bwidth ( bmp -- w ) bdim drop ; : bdata ( bmp -- addr ) 2 cells + ;   : bitmap ( w h -- bmp ) 2dup * pixels bdata allocate throw dup >r 2! r>...
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...
#Groovy
Groovy
class Bell { private static class BellTriangle { private List<Integer> arr   BellTriangle(int n) { int length = (int) (n * (n + 1) / 2) arr = new ArrayList<>(length) for (int i = 0; i < length; ++i) { arr.add(0) }   set(1, 0...
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 freque...
#Erlang
Erlang
  -module( benfords_law ). -export( [actual_distribution/1, distribution/1, task/0] ).   actual_distribution( Ns ) -> lists:foldl( fun first_digit_count/2, dict:new(), Ns ).   distribution( N ) -> math:log10( 1 + (1 / N) ).   task() -> Total = 1000, Fibonaccis = fib( Total ), Actual_dict = actual_distribution( Fibon...
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 S...
#Delphi
Delphi
  program Bernoulli_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigRationals;   function b(n: Integer): BigRational; begin var a: TArray<BigRational>; SetLength(a, n + 1); for var m := 0 to High(a) do begin a[m] := BigRational.Create(1, m + 1); for var j := m downto 1 do begin...
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 p...
#Arturo
Arturo
binarySearch: function [arr,val,low,high][ if high < low -> return ø mid: shr low+high 1 case [val] when? [< arr\[mid]] -> return binarySearch arr val low mid-1 when? [> arr\[mid]] -> return binarySearch arr val mid+1 high else -> return mid ]   ary: [ 0 1 4 5 6 7 ...
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...
#Crystal
Crystal
def best_shuffle(s) # Fill _pos_ with positions in the order # that we want to fill them. pos = [] of Int32 # g["a"] = [2, 4] implies that s[2] == s[4] == "a" g = s.size.times.group_by { |i| s[i] }   # k sorts letters from low to high count # k = g.sort_by { |k, v| v.length }.map { |k, v| k } # in ...
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 la...
#Haskell
Haskell
import Text.Regex {- The above import is needed only for the last function. It is used there purely for readability and conciseness -}   {- Assigning a string to a 'variable'. We're being explicit about it just for show. Haskell would be able to figure out the type of "world" -} string = "world" :: String
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Icon_and_Unicon
Icon and Unicon
s := "\x00" # strings can contain any value, even nulls s := "abc" # create a string s := &null # destroy a string (garbage collect value of s; set new value to &null) v := s # assignment s == t # expression s equals t s << t # expression s less th...