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/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 |...
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64 (Note the (U)Integer type is 64 bits)   ' FB doesn't have built-in logical shift right or rotation operators ' but, as they're not difficult to implement, I've done so below.   Function lsr(x As Const Integer, y As Const Integer) As Integer Dim As UInteger z = x Return z Shr y End Function   Fun...
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...
#J
J
makeRGB=: 0&$: : (($,)~ ,&3) fillRGB=: makeRGB }:@$ setPixels=: (1&{::@[)`(<"1@(0&{::@[))`]} getPixels=: <"1@[ { ]
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Maple
Maple
bell1:=proc(n) option remember; add(binomial(n-1,k)*bell1(k),k=0..n-1) end: bell1(0):=1:   bell1(50); # 185724268771078270438257767181908917499221852770   combinat[bell](50); # 185724268771078270438257767181908917499221852770   bell1~([$0..20]); # [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 6...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  BellTriangle[n_Integer?Positive] := NestList[Accumulate[# /. {a___, b_} :> {b, a, b}] &, {1}, n - 1]; BellNumber[n_Integer] := BellTriangle[n][[n, 1]];  
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...
#Groovy
Groovy
def tallyFirstDigits = { size, generator -> def population = (0..<size).collect { generator(it) } def firstDigits = [0]*10 population.each { number -> firstDigits[(number as String)[0] as int] ++ } firstDigits }
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...
#Haskell
Haskell
import qualified Data.Map as M import Data.Char (digitToInt)   fstdigit :: Integer -> Int fstdigit = digitToInt . head . show   n = 1000 :: Int   fibs = 1 : 1 : zipWith (+) fibs (tail fibs)   fibdata = map fstdigit $ take n fibs   freqs = M.fromListWith (+) $ zip fibdata (repeat 1)   tab :: [(Int, Double, Double)] tab ...
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...
#Frink
Frink
BernoulliNumber[n] := { a = new array for m = 0 to n { a@m = 1/(m+1) for j = m to 1 step -1 a@(j-1) = j * (a@(j-1) - a@j) }   return a@0 }   result = new array for n=0 to 60 { b = BernoulliNumber[n] if b != 0 { [num,den] = numeratorDenominator[b] result.push[[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...
#Batch_File
Batch File
  @echo off & setlocal enabledelayedexpansion   :: Binary Chop Algorithm - Michael Sanders 2017 :: :: example output... :: :: binary chop algorithm vs. standard for loop :: :: number to find 941 :: for loop required 941 iterations :: binchop required 10 iterations   :setup   set x=1 set y=999 set /a z=(%random...
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...
#FutureBasic
FutureBasic
    include "Tlbx GameplayKit.incl" include "NSLog.incl"   local fn ShuffleString( string as CFStringRef ) as CFStringRef NSInteger i   CFMutableArrayRef mutArr = fn MutableArrayWithCapacity( 0 ) for i = 0 to fn StringLength( string ) - 1 MutableArrayAddObject( mutArr, fn StringSubstringWithRange( string, fn CFRangeMak...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"}   func main() { rand.Seed(time.Now().UnixNano()) for _, s := range ts { // create shuffled byte array of original string t := make([]byte, len(s)) for ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Lingo
Lingo
-- String creation and destruction foo = "Hello world!" -- created by assignment; destruction via garbage collection   -- Strings are binary safe put numtochar(0) into char 6 of foo put chartonum(foo.char[6]) -- 0 put str.char[7..foo.length] -- "world!"   -- String cloning and copying bar = foo -- copies foo contents t...
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...
#Lua
Lua
foo = 'foo' -- Ducktyping foo to be string 'foo' bar = 'bar' assert (foo == "foo") -- Comparing string var to string literal assert (foo ~= bar) str = foo -- Copy foo contents to str if #str == 0 then -- # operator returns string length print 'str is empty' end str=str..string.char...
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] ...
#Wren
Wren
import "/sort" for Find import "/fmt" for Fmt   var getBins = Fn.new { |limits, data| var n = limits.count var bins = List.filled(n+1, 0) for (d in data) { var res = Find.all(limits, d) // uses binary search var found = res[0] var index = res[2].from if (found) index = index ...
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 ...
#AWK
AWK
BEGIN { print tobinary(5) print tobinary(50) print tobinary(9000) }   function tobinary(num) { outstr = "" l = num while ( l ) { if ( l%2 == 0 ) { outstr = "0" outstr } else { outstr = "1" outstr } l = int(l/2) } # Make sure we output a zero for a value of zero if ( outstr ...
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.
#Korn_Shell
Korn Shell
function line { x0=$1; y0=$2 x1=$3; y1=$4   if (( x0 > x1 )) then ((dx = x0 - x1)); ((sx = -1)) else ((dx = x1 - x0)); ((sx = 1)) fi   if (( y0 > y1 )) then ((dy = y0 - y1)); ((sy = -1)) else ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PL.2FM
PL/M
IF 0 THEN /* THIS WON'T RUN */; IF 1 THEN /* THIS WILL */; IF 2 THEN /* THIS WON'T */; IF 3 THEN /* THIS WILL */;
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
#Plain_English
Plain English
true false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Pony
Pony
true 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...
#Nim
Nim
import math, sequtils, strformat, strutils   const headingNames: array[1..32, string] = [ "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",...
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 |...
#FutureBasic
FutureBasic
window 1, @"Bitwise Operations", (0,0,650,270)   def fn rotl( b as long, n as long ) as long = ( ( 2^n * b) mod 256) or (b > 127) def fn rotr( b as long, n as long ) as long = (b >> n mod 32) or ( b << (32-n) mod 32)   local fn bitwise( a as long, b as long ) print @"Input: a = "; a; @" b = "; b print print @"AN...
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...
#Java
Java
import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage;   public class BasicBitmapStorage {   private final BufferedImage image;   public BasicBitmapStorage(int width, int height) { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);...
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...
#Nim
Nim
import math   iterator b(): int = ## Iterator yielding the bell numbers. var numbers = @[1] yield 1 var n = 0 while true: var next = 0 for k in 0..n: next += binom(n, k) * numbers[k] numbers.add(next) yield next inc n   when isMainModule:   import strformat   const Limit = 25 ...
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...
#PARIGP
PARIGP
  genit(maxx=50)={bell=List(); for(n=0,maxx,q=sum(k=0,n,stirling(n,k,2)); listput(bell,q));bell} END
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Icon_and_Unicon
Icon and Unicon
global counts, total   procedure main()   counts := table(0) total := 0.0 every benlaw(fib(1 to 1000))   every i := 1 to 9 do write(i,": ",right(100*counts[string(i)]/total,9)," ",100*P(i))   end   procedure benlaw(n) if counts[n ? (tab(upto('123456789')),move(1))] +:= 1 then total +:= 1 end   pro...
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...
#FunL
FunL
import integers.choose   def B( n ) = sum( 1/(k + 1)*sum((if 2|r then 1 else -1)*choose(k, r)*(r^n) | r <- 0..k) | k <- 0..n )   for i <- 0..60 if i == 1 or 2|i printf( "B(%2d) = %s\n", i, B(i) )
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...
#BQN
BQN
BSearch ← { BS ⟨a, value⟩: BS ⟨a, value, 0, ¯1+≠a⟩; BS ⟨a, value, low, high⟩: mid ← ⌊2÷˜low+high { high<low ? ¯1; (mid⊑a)>value ? BS ⟨a, value, low, mid-1⟩; (mid⊑a)<value ? BS ⟨a, value, mid+1, high⟩; mid } }   •Show BSearch ⟨8‿30‿35‿45‿49‿77‿79‿82‿87‿97, 97⟩
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...
#Groovy
Groovy
def shuffle(text) { def shuffled = (text as List) for (sourceIndex in 0..<text.size()) { for (destinationIndex in 0..<text.size()) { if (shuffled[sourceIndex] != shuffled[destinationIndex] && shuffled[sourceIndex] != text[destinationIndex] && shuffled[destinationIndex] != text[sourceInde...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
(* String creation and destruction *) BinaryString = {}; BinaryString = . ; (* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65} -> {12,56,82,65} -> {83,12,56,65} (* String comparison *) BinaryString1 === BinaryString2 -> False (* String cloning and copying *) BinaryString3 = Bi...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
  a=['123',0,' abc ']; b=['456',9]; c='789'; disp(a); disp(b); disp(c);   % string comparison printf('(a==b) is %i\n',strcmp(a,b));   % string copying A = a; B = b; C = c; disp(A); disp(B); disp(C);   % check if string is empty if (length(a)==0) printf('\nstring a is empty\n'); else printf('\nstri...
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 ...
#Axe
Axe
Lbl BIN .Axe supports 16-bit integers, so 16 digits are enough L₁+16→P 0→{P} While r₁ P-- {(r₁ and 1)▶Hex+3}→P r₁/2→r₁ End Disp P,i Return
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.
#Lua
Lua
  ----------------------------------------------- -- Bitmap replacement -- (why? current Lua impl lacks a "set" method) ----------------------------------------------- local Bitmap = { new = function(self, width, height) local instance = setmetatable({ width=width, height=height }, self) instance:alloc() ...
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
#PostScript
PostScript
true false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#PowerShell
PowerShell
$true $false
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Python
Python
>>> True True >>> not True False >>> # As numbers >>> False + 0 0 >>> True + 0 1 >>> False + 0j 0j >>> True * 3.141 3.141 >>> # Numbers as booleans >>> not 0 True >>> not not 0 False >>> not 1234 False >>> bool(0.0) False >>> bool(0j) False >>> bool(1+2j) True >>> # Collections as booleans >>> bool([]) False >>> bool([...
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...
#Objeck
Objeck
  class BoxCompass { function : Main(args : String[]) ~ Nil { points := [ "North ", "North by east ", "North-northeast ", "Northeast by north", "Northeast ", "Northeast by east ", "East-northeast ", "East by north ", "East ", "East by 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 |...
#Go
Go
package main   import "fmt"   func bitwise(a, b int16) { fmt.Printf("a:  %016b\n", uint16(a)) fmt.Printf("b:  %016b\n", uint16(b))   // Bitwise logical operations fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or:  %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", u...
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...
#JavaScript
JavaScript
  // Set up the canvas var canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), width = 400, height = 400;   ctx.canvas.width = width; ctx.canvas.height = height;   // Optionaly add it to the current page document.body.appendChild(canvas);   // Draw an image var img = document.createElement...
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...
#Pascal
Pascal
program BellNumbers; {$Ifdef FPC} {$optimization on,all} {$ElseIf} {Apptype console} {$EndIf} uses sysutils,gmp; var T0 :TDateTime; procedure BellNumbersUint64(OnlyBellNumbers:Boolean); var BList : array[0..24] of Uint64; BellNum : Uint64; BListLenght,i :nativeUInt; begin IF OnlyBellNUmbers then Begin...
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...
#J
J
log10 =: 10&^. benford =: log10@:(1+%) assert '0.30 0.18 0.12 0.10 0.08 0.07 0.06 0.05 0.05' -: 5j2 ": benford >: i. 9     append_next_fib =: , +/@:(_2&{.) assert 5 8 13 -: append_next_fib 5 8   leading_digits =: {.@":&> assert '581' -: leading_digits 5 8 13x   count =: #/.~ /: ~. assert 2 1 3 4 -: count 'XCXBAXACXC' ...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do Print(a, "\n"); od;   [ 0, 1 ] [ 1, -1/2 ] [ 2, 1/6 ] [ 4, -1/30 ] [ 6, 1/42 ] [ 8, -1/30 ] [ 10, 5/66 ] [ 12, -691/2730 ] [ 14, 7/6 ] [ 16, -3617/510 ] [ 18, 43867/798 ] [ 20, -174611/330 ] [ 22, 854513/138 ] [ 24, -236364091/2730 ] [ 26...
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...
#Brat
Brat
binary_search = { search_array, value, low, high | true? high < low { null } { mid = ((low + high) / 2).to_i   true? search_array[mid] > value { binary_search search_array, value, low, mid - 1 } { true? search_array[mid] < value { binary_search search_array, value, mid + 1, high } {...
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...
#Haskell
Haskell
shufflingQuality l1 l2 = length $ filter id $ zipWith (==) l1 l2   printTest prog = mapM_ test texts where test s = do x <- prog s putStrLn $ unwords $ [ show s , show x , show $ shufflingQuality s x] texts = [ "abba", "abracadabra", "seesaw", ...
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...
#Nim
Nim
var # creation x = "this is a string" y = "this is another string" z = "this is a string"   if x == z: echo "x is z" # comparison   z = "now this is another string too" # assignment   y = z # copying   if x.len == 0: echo "empty" # check if empty   x.add('!') # append a byte   echo x[5..8] # substring echo x[8 .....
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...
#OCaml
OCaml
# String.create 10 ;; - : string = "\000\023\000\000\001\000\000\000\000\000"
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 ...
#BaCon
BaCon
' Binary digits OPTION MEMTYPE int INPUT n$ IF VAL(n$) = 0 THEN PRINT "0" ELSE PRINT CHOP$(BIN$(VAL(n$)), "0", 1) ENDIF
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.
#Maple
Maple
SegmentBresenham := proc (img, x0, y0, x1, y1) local deltax, deltay, x, y, ystep, steep, err, img2, x02, y02, x12, y12; x02, x12, y02, y12 := y0, y1, x0, x1; steep := abs(x12 - x02) < abs(y12 - y02); img2 := copy(img); if steep then x02, y02 := y02, x02; x12, y12 := y12, x12; ...
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
#Quackery
Quackery
(cond ([(< 4 3) 'apple] ['bloggle 'pear] [else 'nectarine])
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
#R
R
(cond ([(< 4 3) 'apple] ['bloggle 'pear] [else 'nectarine])
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
#Racket
Racket
(cond ([(< 4 3) 'apple] ['bloggle 'pear] [else 'nectarine])
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...
#OCaml
OCaml
  let test_cases = [0.0; 16.87; 16.88; 33.75; 50.62; 50.63; 67.5; 84.37; 84.38; 101.25; 118.12; 118.13; 135.0; 151.87; 151.88; 168.75; 185.62; 185.63; 202.5; 219.37; 219.38; 236.25; 253.12; 253.13; 270.0; 286.87; 286.88; 303.75; 320.62; 320.63; 337...
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 |...
#Groovy
Groovy
def bitwise = { a, b -> println """ a & b = ${a} & ${b} = ${a & b} a | b = ${a} | ${b} = ${a | b} a ^ b = ${a} ^ ${b} = ${a ^ b} ~ a = ~ ${a} = ${~ a} a << b = ${a} << ${b} = ${a << b} a >> b = ${a} >> ${b} = ${a >> b} arithmetic (sign-preserving) shift 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...
#Julia
Julia
using Images, Colors   Base.hex(p::RGB{T}) where T = join(hex(c(p), 2) for c in (red, green, blue)) function showhex(m::Matrix{RGB{T}}, pad::Integer=4) where T for r in 1:size(m, 1) println(" " ^ pad, join(hex.(m[r, :]), " ")) end end   w, h = 5, 7 cback = RGB(1, 0, 1) cfore = RGB(0, 1, 0)   img = Array...
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...
#KonsolScript
KonsolScript
function main() { Var:Number shape;   Image:New(50, 50, shape) Draw:RectFill(0, 0, 50, 50, 0xFF0000, shape) //one to fill an image with a plain RED color   Draw:Pixel(30, 30, 0x0000FF, shape) //set a given pixel at (30,30) with a BLUE color   while (B1 == false) { Image:Blit(10, 10, shape, scre...
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...
#Perl
Perl
use strict 'vars'; use warnings; use feature 'say'; use bigint;   my @b = 1; my @Aitkens = [1];   push @Aitkens, do { my @c = $b[-1]; push @c, $b[$_] + $c[$_] for 0..$#b; @b = @c; [@c] } until (@Aitkens == 50);   my @Bell_numbers = map { @$_[0] } @Aitkens;   say 'First fifteen and fiftieth Bell numbers:...
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...
#Java
Java
import java.math.BigInteger; import java.util.Locale;   public class BenfordsLaw {   private static BigInteger[] generateFibonacci(int n) { BigInteger[] fib = new BigInteger[n]; fib[0] = BigInteger.ONE; fib[1] = BigInteger.ONE; for (int i = 2; i < fib.length; i++) { fib[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...
#GAP
GAP
for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do Print(a, "\n"); od;   [ 0, 1 ] [ 1, -1/2 ] [ 2, 1/6 ] [ 4, -1/30 ] [ 6, 1/42 ] [ 8, -1/30 ] [ 10, 5/66 ] [ 12, -691/2730 ] [ 14, 7/6 ] [ 16, -3617/510 ] [ 18, 43867/798 ] [ 20, -174611/330 ] [ 22, 854513/138 ] [ 24, -236364091/2730 ] [ 26...
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...
#C
C
#include <stdio.h>   int bsearch (int *a, int n, int x) { int i = 0, j = n - 1; while (i <= j) { int k = i + ((j - i) / 2); if (a[k] == x) { return k; } else if (a[k] < x) { i = k + 1; } else { j = k - 1; } } ret...
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...
#Icon_and_Unicon
Icon and Unicon
# every !t :=: ?t # Uncomment to get a random best shuffling
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...
#PARI.2FGP
PARI/GP
cmp_str(u,v)=u==v copy_str(v)=v \\ Creates a copy, not a pointer append_str(v,n)=concat(v,n) replace_str(source, n, replacement)=my(v=[]);for(i=1,#source,v=concat(v,if(source[i]==n,replacement,source[i]))); v   u=[72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]; v=[]; cmp_str(u,v) w=copy_str(v) #w==0 append_st...
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 ...
#BASIC
BASIC
0 N = 5: GOSUB 1:N = 50: GOSUB 1:N = 9000: GOSUB 1: END 1 LET N2 = ABS ( INT (N)) 2 LET B$ = "" 3 FOR N1 = N2 TO 0 STEP 0 4 LET N2 = INT (N1 / 2) 5 LET B$ = STR$ (N1 - N2 * 2) + B$ 6 LET N1 = N2 7 NEXT N1 8 PRINT B$ 9 RETURN
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Rasterize[Style[Graphics[Line[{{0, 0}, {20, 10}}]], Antialiasing -> 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
#Raku
Raku
my Bool $crashed = False; my $val = 0 but 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
#Raven
Raven
TRUE print FALSE print 2 1 > print # TRUE (-1) 3 2 < print # FALSE (0) 42 FALSE != # TRUE (-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
#REBOL
REBOL
true = 1 false = 0
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#OoRexx
OoRexx
/* Rexx */   Do globs = '!DEG !MIN !SEC !FULL' Drop !DEG !MIN !SEC !FULL sign. = '' sign.!DEG = 'c2b0'x -- degree sign  : U+00B0 sign.!MIN = 'e280b2'x -- prime  : U+2032 sign.!SEC = 'e280b3'x -- double prime : U+2033 points. = ''   Call display_compass_points   Call display_sample Say ...
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 |...
#Harbour
Harbour
  PROCEDURE Main(...) local n1 := 42, n2 := 2 local aPar := hb_AParams() local nRot   if ! Empty( aPar ) n1 := Val( aPar[1] ) hb_Adel( aPar, 1, .T. ) if ! Empty( aPar ) n2 := Val( aPar[1] ) endif endif clear screen   ? "Bitwise operations with two integers" ? "n1...
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...
#Kotlin
Kotlin
// version 1.1.4-3   import java.awt.Color import java.awt.Graphics import java.awt.image.BufferedImage   class BasicBitmapStorage(width: Int, height: Int) { val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)   fun fill(c: Color) { val g = image.graphics g.color = c g...
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...
#Phix
Phix
with javascript_semantics include mpfr.e function bellTriangle(integer n) -- nb: returns strings to simplify output mpz z = mpz_init(1) string sz = "1" sequence tri = {}, line = {} for i=1 to n do line = prepend(line,mpz_init_set(z)) tri = append(tri,{sz}) for j=2 to length(line...
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...
#JavaScript
JavaScript
const fibseries = n => [...Array(n)] .reduce( (fib, _, i) => i < 2 ? ( fib ) : fib.concat(fib[i - 1] + fib[i - 2]), [1, 1] );   const benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9] .map(val => [val, array .reduce( (sum, item) => sum + ( ...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   func b(n int) *big.Rat { var f big.Rat a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(f.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return f.Set(&a[0]) }   func main() { for n := 0; 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...
#C.23
C#
namespace Search { using System;   public static partial class Extensions { /// <summary>Use Binary Search to find index of GLB for value</summary> /// <typeparam name="T">type of entries and value</typeparam> /// <param name="entries">array of entries</param> /// <param name="value">search value</p...
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...
#J
J
bestShuf =: verb define yy=. <@({~ ?~@#)@I.@= y y C.~ (;yy) </.~ (i.#y) |~ >./#@> yy )   fmtBest=:3 :0 b=. bestShuf y y,', ',b,' (',')',~":+/b=y )  
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...
#Pascal
Pascal
const greeting = 'Hello'; var s1: string; s2: ansistring; s3: pchar; begin { Assignments } s1 := 'Mister Presiden'; (* typo is on purpose. See below! *) { Comparisons } if s2 > 'a' then writeln ('The first letter of ', s1, ' is later than a'); { Cloning and copying } s2 := greeting; { Check if a stri...
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 ...
#Bash
Bash
  function to_binary () { if [ $1 -ge 0 ] then val=$1 binary_digits=()   while [ $val -gt 0 ]; do bit=$((val % 2)) quotient=$((val / 2)) binary_digits+=("${bit}") val=$quotient done echo "${binary_digits[*]}" | rev else ...
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.
#MATLAB
MATLAB
  %screen = Bitmap object %startPoint = [x0,y0] %endPoint = [x1,y1] %color = [red,green,blue]   function bresenhamLine(screen,startPoint,endPoint,color)   if( any(color > 255) ) error 'RGB colors must be between 0 and 255'; end   %Check for vertical line, x0 == x1 if( startPoint(1) == endPoint...
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
#ReScript
ReScript
true = 1 false = 0
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
#Retro
Retro
true = 1 false = 0
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
#REXX
REXX
true = 1 false = 0
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#PARI.2FGP
PARI/GP
box(x)={["North","North by east","North-northeast","Northeast by north","Northeast", "Northeast by east","East-northeast","East by north","East","East by south","East-southeast", "Southeast by east","Southeast","Southeast by south","South-southeast","South by east","South", "South by west","South-southwest","Southwest ...
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 |...
#Haskell
Haskell
import Data.Bits   bitwise :: Int -> Int -> IO () bitwise a b = mapM_ print [ a .&. b , a .|. b , a `xor` b , complement a , shiftL a b -- left shift , shiftR a b -- arithmetic right shift , shift a b -- You can also use the "unified" shift function; -- positive is for left 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...
#Lingo
Lingo
-- Creates a new image object of size 640x480 pixel and 32-bit color depth img = image(640, 480, 32)   -- Fills image with plain red img.fill(img.rect, rgb(255,0,0))   -- Gets the color value of the pixel at point (320, 240) col = img.getPixel(320, 240)   -- Changes the color of the pixel at point (320, 240) to black i...
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Picat
Picat
main => B50=b(50), println(B50[1..18]), println(b50=B50.last), nl.   b(M) = R => A = new_array(M-1), bind_vars(A,0), A[1] := 1, R = [1, 1], foreach(N in 2..M-1) A[N] := A[1], foreach(K in N..-1..2) A[K-1] := A[K-1] + A[K], end, R := R ++ [A[1]] 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...
#PicoLisp
PicoLisp
(de bell (N) (make (setq L (link (list 1))) (do N (setq L (link (make (setq A (link (last L))) (for B L (setq A (link (+ A B))) ) ) ) ) ) ) ) (setq L (bell 51)) (for N 15 (tab (2 -2 -2) N ":" (get L N 1)) ) (p...
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...
#jq
jq
# Generate the first n Fibonacci numbers: 1, 1, ... # Numerical accuracy is insufficient beyond about 1450. def fibonacci(n): # input: [f(i-2), f(i-1), countdown] def fib: (.[0] + .[1]) as $sum | if .[2] <= 0 then empty elif .[2] == 1 then $sum else $sum, ([ .[1], $sum, .[2] - 1...
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...
#Julia
Julia
fib(n) = ([one(n) one(n) ; one(n) zero(n)]^n)[1,2]   ben(l) = [count(x->x==i, map(n->string(n)[1],l)) for i='1':'9']./length(l)   benford(l) = [Number[1:9;] ben(l) log10(1.+1./[1:9;])]
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...
#Haskell
Haskell
import Data.Ratio import System.Environment   main = getArgs >>= printM . defaultArg where defaultArg as = if null as then 60 else read (head as)   printM m = mapM_ (putStrLn . printP) . takeWhile ((<= m) . fst) . filter (\(_, b) -> b /= 0 % 1) . zip [0 ..] $ bernoullis   printP (i, r)...
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...
#C.2B.2B
C++
  template <class T> int binsearch(const T array[], int low, int high, T value) { if (high < low) { return -1; } auto mid = (low + high) / 2; if (value < array[mid]) { return binsearch(array, low, mid - 1, value); } else if (value > array[mid]) { return binsearch(array, 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...
#Java
Java
import java.util.Random;   public class BestShuffle { private final static Random rand = new Random();   public static void main(String[] args) { String[] words = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}; for (String w : words) System.out.println(bestShuffle(w)); } ...
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...
#Perl
Perl
$s = undef; say 'Nothing to see here' if ! defined $s; # 'Nothing to see here' say $s = ''; # '' say 'Empty string' if $s eq ''; # 'Empty string' say $s = 'be'; # 'be' say $t = $s; # 'be' say 'Same' if $t eq $s; ...
http://rosettacode.org/wiki/Binary_digits
Binary digits
Task Create and display the sequence of binary digits for a given   non-negative integer. The decimal value   5   should produce an output of   101 The decimal value   50   should produce an output of   110010 The decimal value   9000   should produce an output of   10001100101000 ...
#Batch_File
Batch File
@echo off :num2bin IntVal [RtnVar] setlocal enableDelayedExpansion set /a n=%~1 set rtn= for /l %%b in (0,1,31) do ( set /a "d=n&1, n>>=1" set rtn=!d!!rtn! ) for /f "tokens=* delims=0" %%a in ("!rtn!") do set rtn=%%a (endlocal & rem -- return values if "%~2" neq "" (set %~2=%rtn%) else echo...
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.
#MAXScript
MAXScript
fn plot img coord steep col = ( if steep then ( swap coord[1] coord[2] ) setPixels img coord col )   fn drawLine img start end col = ( local steep = (abs (end.y - start.y)) > (abs (end.x - start.x))   if steep then ( swap start.x start.y swap end.x end.y )   i...
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
#Ring
Ring
  x = True y = False see "x and y : " + (x and y) + nl see "x or y : " + (x or y) + nl see "not x : " + (not x) + nl  
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
#Ruby
Ruby
  fn main() { // Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`. // Expressions inside `if` and `while` statements must result in type `bool`. There is no // automatic conversion to the boolean type.   let true_value = true; if true_value { printl...
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
#Rust
Rust
  fn main() { // Rust contains a single boolean type: `bool`, represented by the keywords `true` and `false`. // Expressions inside `if` and `while` statements must result in type `bool`. There is no // automatic conversion to the boolean type.   let true_value = true; if true_value { printl...
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...
#Pascal
Pascal
program BoxTheCompass(output);   function compasspoint(angle: real): string; const points: array [1..32] of string = ('North ', 'North by east ', 'North-northeast ', 'Northeast by north', 'Northeast ', 'Northeast by east ', 'East-northeast ', 'East by 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 |...
#HicEst
HicEst
i = IAND(k, j) i = IOR( k, j) i = IEOR(k, j) i = NOT( k )
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...
#LiveCode
LiveCode
  -- create an image container box at the center of the current stack window with default properties create image "test" -- programtically choose the paint bucket tool choose bucket tool -- LiveCode engine has built-in color keywords: set the brushColor to "dark green" -- programtically mouse click...
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...
#Lua
Lua
function Allocate_Bitmap( width, height ) local bitmap = {} for i = 1, width do bitmap[i] = {} for j = 1, height do bitmap[i][j] = {} end end return bitmap end   function Fill_Bitmap( bitmap, color ) for i = 1, #bitmap do for j = 1, #bitmap[1] do ...
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...
#Prolog
Prolog
bell(N, Bell):- bell(N, Bell, [], _).   bell(0, [[1]|T], T, [1]):-!. bell(N, Bell, B, Row):- N1 is N - 1, bell(N1, Bell, [Row|B], Last), next_row(Row, Last).   next_row([Last|Bell], Bell1):- last(Bell1, Last), next_row1(Last, Bell, Bell1).   next_row1(_, [], []):-!. next_row1(X, [Y|Rest], [B|Bel...
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...
#Kotlin
Kotlin
import java.math.BigInteger   interface NumberGenerator { val numbers: Array<BigInteger> }   class Benford(ng: NumberGenerator) { override fun toString() = str   private val firstDigits = IntArray(9) private val count = ng.numbers.size.toDouble() private val str: String   init { for (n i...