task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Icon_and_Unicon
Icon and Unicon
link "rational"   procedure main(args) limit := integer(!args) | 60 every b := bernoulli(i := 0 to limit) do if b.numer > 0 then write(right(i,3),": ",align(rat2str(b),60)) end   procedure bernoulli(n) (A := table(0))[0] := rational(1,1,1) every m := 1 to n do { A[m] := rational(1,m+1,1)...
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...
#Chapel
Chapel
proc binsearch(A:[], value) { var low = A.domain.dim(1).low; var high = A.domain.dim(1).high; while (low <= high) { var mid = (low + high) / 2;   if A(mid) > value then high = mid - 1; else if A(mid) < value then ...
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...
#JavaScript
JavaScript
function raze(a) { // like .join('') except producing an array instead of a string var r= []; for (var j= 0; j<a.length; j++) for (var k= 0; k<a[j].length; k++) r.push(a[j][k]); return r; } function shuffle(y) { var len= y.length; for (var j= 0; j < len; j++) { var i= Math.floor(Mat...
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...
#Phix
Phix
with javascript_semantics string s = "abc" s = x"ef bb bf" -- explicit binary string (the utf8 BOM) s[2] = 0 s[3] = 'z' if s="\#EF\0z" then puts(1,"ok\n") end if string t = s t[1..2] = "xy" -- s remains unaltered ?t -- "xyz" t = "food" ?t t[2..3] = 'e' ?t -- "feed" t[3..2] = "ast" ?t -- "feasted" t...
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 ...
#bc
bc
obase = 2 5 50 9000 quit
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Metal
Metal
void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end);   void drawLine(texture2d<float, access::write> targetTexture, uint2 start, uint2 end) { int x = int(start.x); int y = int(start.y);   int dx = abs(x - int(end.x)); int dy = abs(y - int(end.y));   int sx = start.x ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Sather
Sather
v:BOOL := true; -- ok i:INT := 1; v := 1; -- wrong if i then ... end; -- wrong: if requires a bool! -- BUT v := 1.bool; -- ok if i.bool then ... end; -- ok
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Scala
Scala
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Scheme
Scheme
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Perl
Perl
use utf8;   my @names = ( "North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South...
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 |...
#HPPPL
HPPPL
EXPORT BITOPS(a, b) BEGIN PRINT(BITAND(a, b)); PRINT(BITOR(a, b)); PRINT(BITXOR(a, b)); PRINT(BITNOT(a)); PRINT(BITSL(a, b)); PRINT(BITSR(a, b)); // HPPPL has no builtin rotates or arithmetic right shift. END;
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#M2000_Interpreter
M2000 Interpreter
  \ Bitmap width in pixels, height in pixels \ Return a group object with some lambda as members: SetPixel, GetPixel, Image$ \ copyimage \ using Copy x, y Use Image$ we can display image$ to x, y as twips \ we can use x*twipsx, y*twipsy for x,y as pixels Function Bitmap (x as long, y as long) { if x<1 or y<1 ...
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...
#Maple
Maple
allocateImg := proc(width, height) return Array(1..width, 1..height, 1..3); end proc: fillColor := proc(img, rgb::list) local i; for i from 1 to 3 do img[..,..,i] := map(x->rgb[i], img[..,..,i]): end do: end proc: setColor := proc(x, y, img, rgb::list) local i: for i from 1 to 3 do img[x,y,i] := rgb[i]: end ...
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...
#Python
Python
def bellTriangle(n): tri = [None] * n for i in xrange(n): tri[i] = [0] * i tri[1][0] = 1 for i in xrange(2, n): tri[i][0] = tri[i - 1][i - 2] for j in xrange(1, i): tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] return tri   def main(): bt = bellTriangle(51) ...
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...
#Quackery
Quackery
[ ' [ [ 1 ] ] ' [ 1 ] rot 1 - times [ dup -1 peek nested swap witheach [ over -1 peek + join ] tuck nested join swap ] drop ] is bell's-triangle ( n --> [ )   [ bell's-triangle [] swap witheach [ 0 peek join ] ] is bell-numbers ( n --> [ )...
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...
#Liberty_BASIC
Liberty BASIC
  dim bin(9)   N=1000 for i = 0 to N-1 num$ = str$(fiboI(i)) d=val(left$(num$,1)) 'print num$, d bin(d)=bin(d)+1 next print   print "Digit", "Actual freq", "Expected freq" for i = 1 to 9 print i, bin(i)/N, using("#.###", P(i)) next     function P(d) P = log10(d+1)-log10(d) end function   functio...
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...
#J
J
B=: {.&1 %. (i. ! ])@>:@i.@x:
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Clojure
Clojure
(defn bsearch ([coll t] (bsearch coll 0 (dec (count coll)) t)) ([coll l u t] (if (> l u) -1 (let [m (quot (+ l u) 2) mth (nth coll m)] (cond ; the middle element is greater than t ; so search the lower half (> mth t) (recur coll l (dec m) t) ; the middle...
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...
#jq
jq
def count(s): reduce s as $i (0;.+1);   def swap($i;$j): .[$i] as $x | .[$i] = .[$j] | .[$j] = $x;   # Input: an array # Output: a best shuffle def bestShuffleArray: . as $s | reduce range(0; length) as $i (.; . as $t | (first(range(0; length) | select( $i != . and ...
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...
#Julia
Julia
# v0.6   function bestshuffle(str::String)::Tuple{String,Int} s = Vector{Char}(str)   # Count the supply of characters. cnt = Dict{Char,Int}(c => 0 for c in s) for c in s; cnt[c] += 1 end   # Allocate the result r = similar(s) for (i, x) in enumerate(s) # Find the best character to r...
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...
#Picat
Picat
main =>  % - String assignment S1 = "binary_string", println(s1=S1),    % Picat has re-assignments (:=/2) as well, S1 := "another string", println(s1=S1),    % - String comparison if S1 == "another string" then println(same) else println(not_same) end,    % - String cloning and copying S2 =...
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...
#PicoLisp
PicoLisp
: (out "rawfile" (mapc wr (range 0 255)) )
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 ...
#BCPL
BCPL
get "libhdr"   let writebin(x) be $( let f(x) be $( if x>1 then f(x>>1) wrch((x & 1) + '0') $) f(x) wrch('*N') $)   let start() be $( writebin(5) writebin(50) writebin(9000) $)
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Nim
Nim
import bitmap   proc drawLine*(img: Image; p, q: Point; color: Color) = let dx = abs(q.x - p.x) sx = if p.x < q.x: 1 else: -1 dy = abs(q.y - p.y) sy = if p.y < q.y: 1 else: -1   var p = p q = q err = (if dx > dy: dx else: -dy) div 2 e2 = 0   while true: img[p.x, p.y] = color ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Seed7
Seed7
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Self
Self
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#SenseTalk
SenseTalk
repeat with each item of [True, False, Yes, No, On, Off, ""] put it & " is " & (it is true) end repeat  
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Phix
Phix
with javascript_semantics function get225(integer d, string p1, string p2, string p4) string p3 = p1&'-'&lower(p2) p2 &= " by "&lower(p1) p1 &= " by "&lower(p4) if d then return {p1,p3,p2} -- eg {North by east,North-northeast,Northeast by north} else return {p2,p3...
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 |...
#Icon_and_Unicon
Icon and Unicon
procedure main() bitdemo(255,2) bitdemo(-15,3) end   procedure bitdemo(i,i2) write() demowrite("i",i) demowrite("i2",i2) demowrite("complement i",icom(i)) demowrite("i or i2",ior(i,i2)) demowrite("i and i2",iand(i,i2)) demowrite("i xor i2",ixor(i,i2)) demowrite("i shift " || i2,ishift(i,i2)...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
img = Image[ConstantArray[{1, 0, 0}, {1000, 1000}]]; img = ReplacePart[img, {1, 1, 1} -> {0, 0, 1}]; ImageValue[img, {1, 1}]
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#MATLAB
MATLAB
  %Bitmap class % %Implements a class to manage bitmap images without the need for the %various conversion and display functions % %Available functions: % %fill(obj,color) %setPixel(obj,pixel,color) %getPixel(obj,pixel,[optional: color channel]) %display(obj) %disp(obj) %plot(obj) %image(obj) %save(obj) %open(obj)   cl...
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...
#Racket
Racket
#lang racket   (define (build-bell-row previous-row) (define seed (last previous-row)) (reverse (let-values (((reversed _) (for/fold ((acc (list seed)) (prev seed)) ((pprev previous-row)) (let ((n (+ prev pprev))) (values (cons n acc) n)))))...
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...
#Raku
Raku
my @Aitkens-array = lazy [1], -> @b { my @c = @b.tail; @c.push: @b[$_] + @c[$_] for ^@b; @c } ... *;   my @Bell-numbers = @Aitkens-array.map: { .head };   say "First fifteen and fiftieth Bell numbers:"; printf "%2d: %s\n", 1+$_, @Bell-numbers[$_] for flat ^15, 49;   say "\nFirst ten rows of Aitken's a...
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...
#Lua
Lua
actual = {} expected = {} for i = 1, 9 do actual[i] = 0 expected[i] = math.log10(1 + 1 / i) end   n = 0 file = io.open("fibs1000.txt", "r") for line in file:lines() do digit = string.byte(line, 1) - 48 actual[digit] = actual[digit] + 1 n = n + 1 end file:close()   print("digit actual expected") f...
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...
#Java
Java
import org.apache.commons.math3.fraction.BigFraction;   public class BernoulliNumbers {   public static void main(String[] args) { for (int n = 0; n <= 60; n++) { BigFraction b = bernouilli(n); if (!b.equals(BigFraction.ZERO)) System.out.printf("B(%-2d) = %-1s%n", n ,...
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...
#CLU
CLU
% Binary search in an array % If the item is found, returns `true' and the index; % if the item is not found, returns `false' and the leftmost insertion point % The datatype must support the < and > operators. binary_search = proc [T: type] (a: array[T], val: T) returns (bool, int) where T has lt: proct...
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...
#Kotlin
Kotlin
import java.util.Random   object BestShuffle { operator fun invoke(s1: String) : String { val s2 = s1.toCharArray() s2.shuffle() for (i in s2.indices) if (s2[i] == s1[i]) for (j in s2.indices) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1...
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...
#PL.2FI
PL/I
  /* PL/I has immediate facilities for all those operations except for */ /* replace. */ s = t; /* assignment */ s = t || u; /* catenation - append one or more bytes. */ if length(s) = 0 then ... /* test for an empty string. */ if s = t then ... /* compare strin...
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...
#PowerShell
PowerShell
  Clear-Host   ## String creation (which is string assignment): Write-Host "`nString creation (which is string assignment):" -ForegroundColor Cyan Write-Host '[string]$s = "Hello cruel world"' -ForegroundColor Yellow [string]$s = "Hello cruel world"   ## String (or any variable) destruction: Write-Host "`nString (or an...
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 ...
#Beads
Beads
beads 1 program 'Binary Digits' calc main_init loop across:[5, 50, 9000] val:v log to_str(v, base:2)
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#OCaml
OCaml
let draw_line ~img ~color ~p0:(x0,y0) ~p1:(x1,y1) =   let steep = abs(y1 - y0) > abs(x1 - x0) in   let plot = if steep then (fun x y -> put_pixel img color y x) else (fun x y -> put_pixel img color x y) in   let x0, y0, x1, y1 = if steep then y0, x0, y1, x1 else x0, y0, x1, y1 in let...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Sidef
Sidef
var t = true; var f = false;
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Simula
Simula
$!/?\=false= + =true=# \-/
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Slate
Slate
$!/?\=false= + =true=# \-/
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Picat
Picat
go => Names = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south","South-southeast", "South by east", ...
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 |...
#Inform_6
Inform 6
[ bitwise a b temp; print "a and b: ", a & b, "^"; print "a or b: ", a | b, "^"; print "not a: ", ~a, "^"; @art_shift a b -> temp; print "a << b (arithmetic): ", temp, "^"; temp = -b; @art_shift a temp -> temp; print "a >> b (arithmetic): ", temp, "^"; @log_shift a b -> temp; print "a << b (logical)...
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...
#MAXScript
MAXScript
local myBitmap = bitmap 512 512
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Modula-3
Modula-3
INTERFACE Bitmap;   TYPE UByte = BITS 8 FOR [0 .. 16_FF]; Pixel = RECORD R, G, B: UByte; END; Point = RECORD x, y: UByte; END; T = REF ARRAY OF ARRAY OF Pixel;   CONST Black = Pixel{0, 0, 0}; White = Pixel{255, 255, 255}; Red = Pixel{255, 0, 0}; Green = Pixel{0, 255, 0}; Blue = Pixel{0, 0, 255}...
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...
#REXX
REXX
/*REXX program calculates and displays a range of Bell numbers (index starts at zero).*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' & HI=="" then do; LO=0; HI=14; end /*Not specified? Then use the default.*/ if LO=='' | LO=="," then LO= 0 ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
fibdata = Array[First@IntegerDigits@Fibonacci@# &, 1000]; Table[{d, N@Count[fibdata, d]/Length@fibdata, Log10[1. + 1/d]}, {d, 1, 9}] // Grid
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method brenfordDeveation(nlist = Rexx[]) public static observed = 0 loop n_ over nlist d1 = n_.left(1) if d1 = 0 then iterat...
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...
#jq
jq
# def negate: # def lessOrEqual(x; y): # x <= y # def long_add(x;y): # x+y # def long_minus(x;y): # x-y # def long_multiply(x;y) # x*y # def long_divide(x;y): # x/y => [q,r] # def long_div(x;y) # integer division # def long_mod(x;y) # %   # In all cases, x and y must be strings   def negate: (- tonumbe...
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...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. binary-search.   DATA DIVISION. WORKING-STORAGE SECTION. 01 nums-area VALUE "01040612184356". 03 nums PIC 9(2) OCCURS 7 TIMES ...
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...
#Liberty_BASIC
Liberty BASIC
'see Run BASIC solution list$ = "abracadabra seesaw pop grrrrrr up a"   while word$(list$,ii + 1," ") <> "" ii = ii + 1 w$ = word$(list$,ii," ") bs$ = bestShuffle$(w$) count = 0 for i = 1 to len(w$) if mid$(w$,i,1) = mid$(bs$,i,1) then count = count + 1 next i print w$;" ";bs$;" ";count wend   functio...
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...
#Prolog
Prolog
% Create a string (no destruction necessary) ?- X = "a test string". X = "a test string".   % String assignment, there is no assignment but you can unify between variables, also 'String cloning and copying' ?- X = "a test string", X = Y. X = Y, Y = "a test string".   % String comparison ?- X = "a test string", Y = "a 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 ...
#Befunge
Befunge
&>0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Pascal
Pascal
#! /usr/bin/perl use strict; use Image::Imlib2;   sub my_draw_line { my ( $img, $x0, $y0, $x1, $y1) = @_;   my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { ( $y0, $x0 ) = ( $x0, $y0); ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { ( $x1, $x0 ) = ( $x0, $x1 ); ( $y1, $y0 ) =...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Smalltalk
Smalltalk
$!/?\=false= + =true=# \-/
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#SNUSP
SNUSP
$!/?\=false= + =true=# \-/
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#SPL
SPL
datatype bool = false | true
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#PicoLisp
PicoLisp
(scl 3)   (setq *Compass # Build lookup table (let H -16.875 (mapcar '((Str) (cons (inc 'H 11.25) # Heading in degrees (pack # Compass point (replace (chop Str) "N" "north" ...
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 |...
#J
J
bAND=: 17 b. NB. 16+#.0 0 0 1 bOR=: 23 b. NB. 16+#.0 1 1 1 bXOR=: 22 b. NB. 16+#.0 1 1 0 b1NOT=: 28 b. NB. 16+#.1 1 0 0 bLshift=: 33 b.~ NB. see http://www.jsoftware.com/help/release/bdot.htm bRshift=: 33 b.~ - bRAshift=: 34 b.~ - bLrot=: 32 b.~ bRrot=: 32 b.~ -
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Nim
Nim
type Luminance* = uint8 Index* = int   Color* = tuple r, g, b: Luminance   Image* = ref object w*, h*: Index pixels*: seq[Color]   Point* = tuple x, y: Index   proc color*(r, g, b: SomeInteger): Color = ## Build a color value from R, G and B values. result.r = r.uint8 result.g = g.uint8 ...
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...
#OCaml
OCaml
let new_img ~width ~height = let all_channels = let kind = Bigarray.int8_unsigned and layout = Bigarray.c_layout in Bigarray.Array3.create kind layout 3 width height in let r_channel = Bigarray.Array3.slice_left_2 all_channels 0 and g_channel = Bigarray.Array3.slice_left_2 all_channels 1 and b...
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...
#Ruby
Ruby
def bellTriangle(n) tri = Array.new(n) for i in 0 .. n - 1 do tri[i] = Array.new(i) for j in 0 .. i - 1 do tri[i][j] = 0 end end tri[1][0] = 1 for i in 2 .. n - 1 do tri[i][0] = tri[i - 1][i - 2] for j in 1 .. i - 1 do tri[i][j] = tri[i...
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...
#Nim
Nim
import math import strformat   type   # Non zero digit range. Digit = range[1..9]   # Count array used to compute a distribution. Count = array[Digit, Natural]   # Array to store frequencies. Distribution = array[Digit, float]     #############################################################################...
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...
#Oberon-2
Oberon-2
  MODULE BenfordLaw; IMPORT LRealStr, LRealMath, Out := NPCT:Console;   VAR r: ARRAY 1000 OF LONGREAL; d: ARRAY 10 OF LONGINT; a: LONGREAL; i: LONGINT;   PROCEDURE Fibb(VAR r: ARRAY OF LONGREAL); VAR i: LONGINT; BEGIN r[0] := 1.0;r[1] := 1.0; FOR i := 2 TO LEN(r) - 1 DO r[i] := r[i - 2] + r[i -...
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...
#Julia
Julia
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for m = 0 : n A[m + 1] = 1 // (m + 1) for j = m : -1 : 1 A[j] = j * (A[j] - A[j + 1]) end end return A[1] end   function display(n) B = map(bernoulli, 0 : n) pad = mapreduce(x -> ndigits(numerato...
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...
#CoffeeScript
CoffeeScript
binarySearch = (xs, x) -> do recurse = (low = 0, high = xs.length - 1) -> mid = Math.floor (low + high) / 2 switch when high < low then NaN when xs[mid] > x then recurse low, mid - 1 when xs[mid] < x then recurse mid + 1, high else mid
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Lua
Lua
math.randomseed(os.time())   local function shuffle(t) for i = #t, 2, -1 do local j = math.random(i) t[i], t[j] = t[j], t[i] end end   local function bestshuffle(s, r) local order, shufl, count = {}, {}, 0 for ch in s:gmatch(".") do order[#order+1], shufl[#shufl+1] = ch, ch end if r then shuffle(shufl...
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...
#PureBasic
PureBasic
  ;string creation x$ = "hello world"   ;string destruction x$ = ""   ;string comparison If x$ = "hello world" : PrintN("String is equal") : EndIf   ;string copying; y$ = x$   ; check If empty If x$ = "" : PrintN("String is empty") : EndIf   ; append a byte x$ = x$ + Chr(41)   ; extract a substring x$ = Mid(x$, 1, 5)...
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 ...
#BQN
BQN
Bin ← 2{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}   Bin¨5‿50‿9000
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Perl
Perl
#! /usr/bin/perl use strict; use Image::Imlib2;   sub my_draw_line { my ( $img, $x0, $y0, $x1, $y1) = @_;   my $steep = (abs($y1 - $y0) > abs($x1 - $x0)); if ( $steep ) { ( $y0, $x0 ) = ( $x0, $y0); ( $y1, $x1 ) = ( $x1, $y1 ); } if ( $x0 > $x1 ) { ( $x1, $x0 ) = ( $x0, $x1 ); ( $y1, $y0 ) =...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Standard_ML
Standard ML
datatype bool = false | true
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Stata
Stata
% if {""} then {puts true} else {puts false} expected boolean value but got ""
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#PowerShell
PowerShell
function Convert-DegreeToDirection ( [double]$Degree ) {   $Directions = @( 'n','n by e','n-ne','ne by n','ne','ne by e','e-ne','e by n', 'e','e by s','e-se','se by e','se','se by s','s-se','s by e', 's','s by w','s-sw','sw by s','sw','sw by w','w-sw','w by s',...
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 |...
#Java
Java
public static void bitwise(int a, int b){ System.out.println("a AND b: " + (a & b)); System.out.println("a OR b: "+ (a | b)); System.out.println("a XOR b: "+ (a ^ b)); System.out.println("NOT a: " + ~a); System.out.println("a << b: " + (a << b)); // left shift System.out.println("a >> b: " + (a >> b)); // 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...
#Octave
Octave
im = zeros(W, H, 3, "uint8"); % create an RGB image of width W and height H % and intensity from 0 to 255; black (all zeros) im(:,:,1) = 255; % set R to 255 im(:,:,2) = 100; % set G to 100 im(:,:,3) = 155; % set B to 155 im(floor(W/2), floor(H/2), :) ...
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...
#Rust
Rust
use num::BigUint;   fn main() { let bt = bell_triangle(51); // the fifteen first for i in 1..=15 { println!("{}: {}", i, bt[i][0]); }   // the fiftieth println!("50: {}", bt[50][0]) }   fn bell_triangle(n: usize) -> Vec<Vec<BigUint>> { let mut tri: Vec<Vec<BigUint>> = Vec::with_capac...
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...
#Scala
Scala
import scala.collection.mutable.ListBuffer   object BellNumbers { class BellTriangle { val arr: ListBuffer[Int] = ListBuffer.empty[Int]   def this(n: Int) { this()   val length = n * (n + 1) / 2 for (_ <- 0 until length) { arr += 0 }   this (1, 0) = 1 for (i <- 2 to...
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...
#OCaml
OCaml
  open Num   let fib = let rec fib_aux f0 f1 = function | 0 -> f0 | 1 -> f1 | n -> fib_aux f1 (f1 +/ f0) (n - 1) in fib_aux (num_of_int 0) (num_of_int 1) ;;   let create_fibo_string = function n -> string_of_num (fib n) ;; let rec range i j = if i > j then [] else i :: (range (i + 1) j)   let n_max = ...
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...
#Kotlin
Kotlin
import org.apache.commons.math3.fraction.BigFraction   object Bernoulli { operator fun invoke(n: Int) : BigFraction { val A = Array(n + 1, init) for (m in 0..n) for (j in m downTo 1) A[j - 1] = A[j - 1].subtract(A[j]).multiply(integers[j]) return A.first() }  ...
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...
#Common_Lisp
Common Lisp
(defun binary-search (value array) (let ((low 0) (high (1- (length array))))   (do () ((< high low) nil) (let ((middle (floor (+ low high) 2)))   (cond ((> (aref array middle) value) (setf high (1- middle)))   ((< (aref array middle) value) (setf l...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
BestShuffle[data_] := Flatten[{data,First[SortBy[ List[#, StringLength[data]-HammingDistance[#,data]] & /@ StringJoin /@ Permutations[StringSplit[data, ""]], Last]]}]   Print[#[[1]], "," #[[2]], ",(", #[[3]], ")"] & /@ BestShuffle /@ {"abracadabra","seesaw","elk","grrrrrr","up","a"}  
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Nim
Nim
import times import sequtils import strutils import random   proc count(s1, s2: string): int = for i, c in s1: if c == s2[i]: result.inc   proc shuffle(str: string): string = var r = initRand(getTime().toUnix()) var chrs = toSeq(str.items) for i in 0 ..< chrs.len: let chosen ...
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...
#Python
Python
s1 = "A 'string' literal \n" s2 = 'You may use any of \' or " as delimiter' s3 = """This text goes over several lines up to the closing triple quote"""
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Racket
Racket
  #lang racket   ;; Byte strings can be created either by a function (b1) ;; or as a literal string (b2). No operation is needed for ;; destruction due to garbage collection.   (define b1 (make-bytes 5 65))  ; b1 -> #"AAAAA" (define b2 #"BBBBB")  ; b2 -> #"BBBBB"   ;; String assignment. Note that b2 cannot be ...
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 ...
#Bracmat
Bracmat
( dec2bin = bit bits .  :?bits & whl ' ( !arg:>0 & mod$(!arg,2):?bit & div$(!arg,2):?arg & !bit !bits:?bits ) & (str$!bits:~|0) ) & 0 5 50 9000 423785674235000123456789:?numbers & whl ' ( !numbers:%?dec ?numbers & put$(str$(!dec ":\n" de...
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Phix
Phix
-- demo\rosetta\Bresenham_line.exw (runnable version)   global function bresLine(sequence image, integer x0, y0, x1, y1, colour) -- The line algorithm integer dimx = length(image), dimy = length(image[1]), deltaX = abs(x1-x0), deltaY = abs(y1-y0), stepX = iff(x0<x...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Swift
Swift
% if {""} then {puts true} else {puts false} expected boolean value but got ""
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Tcl
Tcl
% if {""} then {puts true} else {puts false} expected boolean value but got ""
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Trith
Trith
if echo 'Looking for file' # This is the evaluation block test -e foobar.fil # The exit code from this statement determines whether the branch runs then echo 'The file exists' # This is the optional branch echo 'I am going to delete it' rm foobar.fil fi
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Prolog
Prolog
  compassangle(1, 'North',n, 0.00). compassangle(2, 'North by east', nbe, 11.25). compassangle(3, 'North-northeast', nne,22.50). compassangle(4, 'Northeast by north', nebn,33.75). compassangle(5, 'Northeast', ne,45.00). compassangle(6, 'Norteast by east', nebe,56.25). compassangle(7, 'East-northeast', ene,67.50). compa...
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 |...
#JavaScript
JavaScript
function bitwise(a, b){ alert("a AND b: " + (a & b)); alert("a OR b: "+ (a | b)); alert("a XOR b: "+ (a ^ b)); alert("NOT a: " + ~a); alert("a << b: " + (a << b)); // left shift alert("a >> b: " + (a >> b)); // arithmetic right shift alert("a >>> b: " + (a >>> b)); // logical right shift }
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#OxygenBasic
OxygenBasic
  'GENERIC BITMAP   type pixel byte r,g,b   '=========== class BitMap '===========   % sp sizeof(pixel) sys wx,wy,px,py string buf sys pb method Constructor(sys x=640,y=480) { wx=x : wy=y : buf=nuls x*y*sp : pb=strptr buf} method Destructor() {buf="" : wx=0 : wy=0 : pb=0} method GetPixel(sys x,y...
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...
#Oz
Oz
functor export New Get Set Transform define fun {New Width Height Init} C = {Array.new 1 Height unit} in for Row in 1..Height do C.Row := {Array.new 1 Width Init} end   array2d(width:Width height:Height contents:C) end   fun {Get array2d(contents:C ...) X ...
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...
#Scheme
Scheme
; Given the remainder of the previous row and the final cons of the current row, ; extend (in situ) the current row to be a complete row of the Bell triangle. ; Return the final value in the extended row (for use in computing the following row).   (define bell-triangle-row-extend (lambda (prevrest thisend) (cond ...
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...
#PARI.2FGP
PARI/GP
distribution(v)={ my(t=vector(9,n,sum(i=1,#v,v[i]==n))); print("Digit\tActual\tExpected"); for(i=1,9,print(i, "\t", t[i], "\t", round(#v*(log(i+1)-log(i))/log(10)))) }; dist(f)=distribution(vector(1000,n,digits(f(n))[1])); lucas(n)=fibonacci(n-1)+fibonacci(n+1); dist(fibonacci) dist(lucas)
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Lua
Lua
#!/usr/bin/env luajit local gmp = require 'gmp' ('libgmp') local ffi = require'ffi' local mpz, mpq = gmp.types.z, gmp.types.q local function mpq_for(buf, op, n) for i=0,n-1 do op(buf[i]) end end local function bernoulli(rop, n) local a=ffi.new("mpq_t[?]", n+1) mpq_for(a, gmp.q_init, n+1)   for m=0,n do gmp.q_s...
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Crystal
Crystal
class Array def binary_search(val, low = 0, high = (size - 1)) return nil if high < low #mid = (low + high) >> 1 mid = low + ((high - low) >> 1) case val <=> self[mid] when -1 binary_search(val, low, mid - 1) when 1 binary_search(val, mid + 1, high) else mid end ...