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/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...
#OCaml
OCaml
let best_shuffle s = let len = String.length s in let r = String.copy s in for i = 0 to pred len do for j = 0 to pred len do if i <> j && s.[i] <> r.[j] && s.[j] <> r.[i] then begin let tmp = r.[i] in r.[i] <- r.[j]; r.[j] <- tmp; end done; done; (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...
#Raku
Raku
# Raku is perfectly fine with NUL *characters* in strings: my Str $s = 'nema' ~ 0.chr ~ 'problema!'; say $s;   # However, Raku makes a clear distinction between strings # (i.e. sequences of characters), like your name, or … my Str $str = "My God, it's full of chars!"; # … and sequences of bytes (called Bufs), for examp...
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 ...
#Brainf.2A.2A.2A
Brainf***
+[ Start with n=1 to kick off the loop [>>++<< Set up {n 0 2} for divmod magic [->+>- Then [>+>>]> do [+[-<+>]>+>>] the <<<<<<] magic >>>+ Increment n % 2 so that 0s don't break things >] Move into n / 2 and divmod that unless it's 0 -< Set up sentinel ...
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.
#PicoLisp
PicoLisp
(de brez (Img X Y DX DY) (let SX (cond ((=0 DX) 0) ((gt0 DX) 1) (T (setq DX (- DX)) -1) ) (let SY (cond ((=0 DY) 0) ((gt0 DY) 1) (T (setq DY (- DY)) -1) ) (if (>= DX DY) (let E (- (* 2 DY) DX) (do ...
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
#UNIX_Shell
UNIX Shell
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/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
#Ursa
Ursa
decl boolean bool
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
#VBA
VBA
Dim a As Integer Dim b As Boolean Debug.Print b a = b Debug.Print a b = True Debug.Print b a = b Debug.Print a
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...
#PureBasic
PureBasic
DataSection Data.s "N", "north", "E", "east", "W", "west", "S", "south", "b", " by " ;abbreviations, expansions Data.s "N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE" ;dirs Data.s "S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW" EndDataSection   ;initialize data NewMap dir...
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 |...
#Julia
Julia
# Version 5.2 @show 1 & 2 # AND @show 1 | 2 # OR @show 1 ^ 2 # XOR -- for Julia 6.0 the operator is `⊻` @show ~1 # NOT @show 1 >>> 2 # SHIFT RIGHT (LOGICAL) @show 1 >> 2 # SHIFT RIGHT (ARITMETIC) @show 1 << 2 # SHIFT LEFT (ARITMETIC/LOGICAL)   A = BitArray([true, true, false, false, true]) @show A ror(A,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...
#Pascal
Pascal
Interface uses crt, { GetDir } graph; { function GetPixel }   type { integer numbers } { from unit bitmaps XPERT software production Tamer Fakhoury } _bit = $00000000..$00000001; {number 1 bit without sign = (0..1) } _byte = $00000000..$000000FF; {number 1 byte without sign = (0..255)} _word ...
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...
#Sidef
Sidef
say 15.of { .bell }
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Swift
Swift
public struct BellTriangle<T: BinaryInteger> { @usableFromInline var arr: [T]   @inlinable public internal(set) subscript(row row: Int, col col: Int) -> T { get { arr[row * (row - 1) / 2 + col] } set { arr[row * (row - 1) / 2 + col] = newValue } }   @inlinable public init(n: Int) { arr = Array...
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...
#Pascal
Pascal
program fibFirstdigit; {$IFDEF FPC}{$MODE Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; type tDigitCount = array[0..9] of LongInt; var s: Ansistring; dgtCnt, expectedCnt : tDigitCount;   procedure GetFirstDigitFibonacci(var dgtCnt:tDigitCount;n:LongInt=1000); //summing up only the first 9 digits //n...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Maple
Maple
print(select(n->n[2]<>0,[seq([n,bernoulli(n,1)],n=0..60)]));
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
bernoulli[n_] := Module[{a = ConstantArray[0, n + 2]}, Do[ a[[m]] = 1/m; If[m == 1 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; Do[ a[[j - 1]] = (j - 1)*(a[[j - 1]] - a[[j]]); If[j == 2 && a[[1]] != 0, Print[{m - 1, a[[1]]}]]; , {j, m, 2, -1}]; , {m, 1, n + 1}]; ] bernoulli[60]
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...
#D
D
import std.stdio, std.array, std.range, std.traits;   /// Recursive. bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) { if (data.empty) return false; immutable i = data.length / 2; immutable mid = data[i]; if (...
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...
#Pascal
Pascal
program BestShuffleDemo(output);   function BestShuffle(s: string): string;   var tmp: char; i, j: integer; t: string; begin t := s; for i := 1 to length(t) do for j := 1 to length(t) do if (i <> j) and (s[i] <> t[j]) and (s[j] <> t[i]) then begin tmp := t[i]; ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Red
Red
Red [] s: copy "abc" ;; string creation   s: none ;; destruction t: "Abc" if t == "abc" [print "equal case"] ;; comparison , case sensitive if t = "abc" [print "equal (case insensitive)"] ;; comparison , case insensitive s: copy "" ;; copying string if empty? s [pr...
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 ...
#Burlesque
Burlesque
  blsq ) {5 50 9000}{2B!}m[uN 101 110010 10001100101000  
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.
#PL.2FI
PL/I
  /* Draw a line from (x0, y0) to (x1, y1). 13 May 2010 */ /* Based on Rosetta code proforma. */   /* Declarations for image and selected color, for 4-bit colors. */ declare image(40,40) bit (4), color bit (4) static initial ('1000'b);   draw_line: procedure (xi, yi, xf, yf ); declare (xi, yi, xf, yf) fixed ...
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
#VBScript
VBScript
  a = True b = False Randomize Timer x = Int(Rnd * 2) <> 0 y = Int(Rnd * 2) = 0 MsgBox a & " " & b & " " & x & " " & y
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
#Vim_Script
Vim Script
if "foo" echo "true" else echo "false" endif
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
#Vlang
Vlang
// Boolean Value, in V // Tectonics: v run boolean-value.v module main   // V bool type, with values true or false are the V booleans. // true and false are V keywords, and display as true/false // Numeric values are not booleans in V, 0 is not boolean false pub fn main() { t := true f := false   if t { pri...
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...
#Python
Python
majors = 'north east south west'.split() majors *= 2 # no need for modulo later quarter1 = 'N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N'.split(',') quarter2 = [p.replace('NE','EN') for p in quarter1]   def degrees2compasspoint(d): d = (d % 360) + 360/64 majorindex, minor = divmod(d, 90.) majorindex = i...
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Kotlin
Kotlin
/* for symmetry with Kotlin's other binary bitwise operators we wrap Java's 'rotate' methods as infix functions */ infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance)   fun main(args: Array<String>) { // inferred...
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...
#Perl
Perl
#! /usr/bin/perl   use strict;   use Image::Imlib2;   # create the "canvas" my $img = Image::Imlib2->new(200,200);   # fill with a plain RGB(A) color $img->set_color(255, 0, 0, 255); $img->fill_rectangle(0,0, 200, 200);   # set a pixel to green (at 40,40) $img->set_color(0, 255, 0, 255); $img->draw_point(40,40);   # "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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Sub Init(Of T)(array As T(), value As T) If IsNothing(array) Then Return For i = 0 To array.Length - 1 array(i) = value Next End Sub   Function BellTriangle(n As Integer) ...
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...
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use POSIX qw( log10 ) ;   my @fibonacci = ( 0 , 1 ) ; while ( @fibonacci != 1000 ) { push @fibonacci , $fibonacci[ -1 ] + $fibonacci[ -2 ] ; } my @actuals ; my @expected ; for my $i( 1..9 ) { my $sum = 0 ; map { $sum++ if $_ =~ /\A$i/ } @fibonacci ; push @actuals...
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...
#Nim
Nim
import bignum import strformat   const Lim = 60   #---------------------------------------------------------------------------------------------------   proc bernoulli(n: Natural): Rat = ## Compute a Bernoulli number using Akiyama–Tanigawa algorithm.   var a = newSeq[Rat](n + 1) for m in 0..n: a[m] = newRat(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...
#Delphi
Delphi
/** Returns null if the value is not found. */ def binarySearch(collection, value) { var low := 0 var high := collection.size() - 1 while (low <= high) { def mid := (low + high) // 2 def comparison := value.op__cmp(collection[mid]) if (comparison.belowZero()) { high := mid - 1 }...
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Perl
Perl
use strict; use warnings; use List::Util qw(shuffle); use Algorithm::Permute;   best_shuffle($_) for qw(abracadabra seesaw elk grrrrrr up a);   sub best_shuffle { my ($original_word) = @_; my $best_word = $original_word; my $best_score = length $best_word;   my @shuffled = shuffle split //, $original_word; my $ite...
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...
#REXX
REXX
/*REXX program demonstrates methods (code examples) to use and express binary strings.*/ dingsta= '11110101'b /*four versions, bit string assignment.*/ dingsta= "11110101"b /*this is the same assignment as above.*/ dingsta= '11110101'B ...
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 ...
#C
C
#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings #define _CRT_NONSTDC_NO_DEPRECATE // enable old-gold POSIX names in MSVS   #include <stdio.h> #include <stdlib.h>     char* bin2str(unsigned value, char* buffer) { // This algorithm is not the fastest one, but is relativelly simple. // // A fas...
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.
#Prolog
Prolog
  :- use_module(bitmap). :- use_module(bitmapIO). :- use_module(library(clpfd)).   % ends when X1 = X2 and Y1 = Y2 draw_recursive_line(NPict,Pict,Color,X,X,_DX,_DY,Y,Y,_E,_Sx,_Sy):- set_pixel0(NPict,Pict,[X,Y],Color). draw_recursive_line(NPict,Pict,Color,X,X2,DX,DY,Y,Y2,E,Sx,Sy):- set_pixel0(TPict,Pict,[X,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
#WDTE
WDTE
let io => import 'io'; let ex => switch 'this is irrelevant for this example' { false => 'This is, obviously, not returned.'; 'a string' => 'This is also not returned.'; true => 'This is returned.'; }; ex -- io.writeln io.stdout;
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
#Wren
Wren
var embed = true System.printAll([embed, ", ", !embed, ", ", "Is Wren embeddable? " + embed.toString])
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...
#QBasic
QBasic
DECLARE FUNCTION compasspoint$ (h!)   DIM SHARED POINT$(32)   FOR i = 1 TO 32 READ d$: POINT$(i) = d$ NEXT i   FOR i = 0 TO 32 heading = i * 11.25 IF (i MOD 3) = 1 THEN heading = heading + 5.62 ELSE IF (i MOD 3) = 2 THEN heading = heading - 5.62 END IF ind = i MOD 32 + 1 PRIN...
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 |...
#LFE
LFE
(defun bitwise (a b) (lists:map (lambda (x) (io:format "~p~n" `(,x))) `(,(band a b) ,(bor a b) ,(bxor a b) ,(bnot a) ,(bsl a b) ,(bsr a b))) 'ok)   (defun dec->bin (x) (integer_to_list x 2))   (defun describe (func arg1 arg2 result) (io:format "(~s ~s ~s): ~s~n" ...
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Phix
Phix
with javascript_semantics -- Some colour constants: constant black = #000000, -- blue = #0000FF, -- green = #00FF00, -- red = #FF0000, white = #FFFFFF -- Create new image filled with some colour function new_image(integer width, integer height, integer fill_colour=black) return repea...
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...
#Vlang
Vlang
import math.big   fn bell_triangle(n int) [][]big.Integer { mut tri := [][]big.Integer{len: n} for i in 0..n { tri[i] = []big.Integer{len: i} for j in 0..i { tri[i][j] = big.zero_int } } tri[1][0] = big.integer_from_u64(1) for i in 2..n { tri[i][0] = tri[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...
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var bellTriangle = Fn.new { |n| var tri = List.filled(n, null) for (i in 0...n) { tri[i] = List.filled(i, null) for (j in 0...i) tri[i][j] = BigInt.zero } tri[1][0] = BigInt.one for (i in 2...n) { tri[i][0] = tri[i-1][i-2] ...
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Phix
Phix
with javascript_semantics function benford(sequence s, string title) sequence f = repeat(0,9) for i=1 to length(s) do integer fdx = sprint(s[i])[1]-'0' f[fdx] += 1 end for sequence res = {title,"Digit Observed% Predicted%"} for i=1 to length(f) do atom o = f[i]/length(s)*10...
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...
#PARI.2FGP
PARI/GP
for(n=0,60,t=bernfrac(n);if(t,print(n" "t)))
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...
#E
E
/** Returns null if the value is not found. */ def binarySearch(collection, value) { var low := 0 var high := collection.size() - 1 while (low <= high) { def mid := (low + high) // 2 def comparison := value.op__cmp(collection[mid]) if (comparison.belowZero()) { high := mid - 1 }...
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#Phix
Phix
with javascript_semantics constant tests = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} for test=1 to length(tests) do string s = tests[test], t = shuffle(s) for i=1 to length(t) do for j=1 to length(t) do integer {ti,tj} = {t[i],t[j]} if i!=j and ti!=s[j] an...
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...
#Ring
Ring
# string creation x = "hello world"   # string destruction x = NULL   # string assignment with a null byte x = "a"+char(0)+"b" see len(x) # ==> 3   # string comparison if x = "hello" See "equal" else See "not equal" ok y = 'bc' if strcmp(x,y) < 0 See x + " is lexicographically less than " + y ok   # string cloni...
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...
#Ruby
Ruby
# string creation x = "hello world"   # string destruction x = nil   # string assignment with a null byte x = "a\0b" x.length # ==> 3   # string comparison if x == "hello" puts "equal" else puts "not equal" end y = 'bc' if x < y puts "#{x} is lexicographically less than #{y}" end   # string cloning xx = x.dup x...
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 ...
#C.23
C#
using System;   class Program { static void Main() { foreach (var number in new[] { 5, 50, 9000 }) { Console.WriteLine(Convert.ToString(number, 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.
#PureBasic
PureBasic
Procedure BresenhamLine(x0 ,y0 ,x1 ,y1) If Abs(y1 - y0) > Abs(x1 - x0); steep =#True Swap x0, y0 Swap x1, y1 EndIf If x0 > x1 Swap x0, x1 Swap y0, y1 EndIf deltax = x1 - x0 deltay = Abs(y1 - y0) error = deltax / 2 y = y0 If 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
#XLISP
XLISP
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an att...
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
#XPL0
XPL0
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an att...
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...
#Racket
Racket
#lang racket   ;;; Generate the headings and boxes (define (i->heading/box i) (values (let ((heading (* i #e11.25))) (case (modulo i 3) ((1) (+ heading #e5.62)) ((2) (- heading #e5.62)) (else heading))) (add1 (modulo i 32)))) (define-values (headings-list box-list...
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 |...
#Liberty_BASIC
Liberty BASIC
  ' bitwise operations on byte-sized variables   v =int( 256 *rnd( 1))   s = 1   print "Shift ="; s; " place." print print "Number as dec. = "; v; " & as 8-bits byte = ", dec2Bin$( v) print "NOT as dec. = "; bitInvert( v), dec2Bin$( bitInvert( v)) print "Shifted left as dec. = "; shiftL...
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...
#PHP
PHP
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } //Fills a rectangle, or the whole image with black by default public fu...
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...
#zkl
zkl
fcn bellTriangleW(start=1,wantRow=False){ // --> iterator Walker.zero().tweak('wrap(row){ row.insert(0,row[-1]); foreach i in ([1..row.len()-1]){ row[i]+=row[i-1] } wantRow and row or row[-1] }.fp(List(start))).push(start,start); }
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...
#Picat
Picat
go =>   N = 1000, Fib = [fib(I) : I in 1..N], check_benford(Fib), nl.   % Check a list of numbers for Benford's law check_benford(L) => Len = L.len, println(len=Len), Count = [F[1].to_integer() : Num in L, F=Num.to_string()].occurrences(), P = new_map([I=D/Len : I=D in Count]), println("Benford (perce...
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...
#PicoLisp
PicoLisp
  (scl 4) (load "@lib/misc.l") (load "@lib/math.l")   (setq LOG10E 0.4343)   (de fibo (N) (let (A 0 B 1 C NIL) (make (link B) (do (dec N) (setq C (+ A B) A B B C) (link B)))))   (setq Actual (let ( Digits (sort (mapcar '((N) (format (car (chop N)))) (fibo...
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...
#Pascal
Pascal
  (* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *)   program BernoulliForAda99;   uses BigDecimalMath; {library for arbitary high precision BCD numbers}   type Fraction = object private numerator, denominator: BigDecimal;   public procedure assign(n, d: Int64); procedure sub...
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...
#EasyLang
EasyLang
func bin_search val . a[] res . low = 0 high = len a[] - 1 res = -1 while low <= high and res = -1 mid = (low + high) div 2 if a[mid] > val high = mid - 1 elif a[mid] < val low = mid + 1 else res = mid . . . a[] = [ 2 4 6 8 9 ] call bin_search 8 a[] r print r
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...
#PHP
PHP
foreach (split(' ', 'abracadabra seesaw pop grrrrrr up a') as $w) echo bestShuffle($w) . '<br>';   function bestShuffle($s1) { $s2 = str_shuffle($s1); for ($i = 0; $i < strlen($s2); $i++) { if ($s2[$i] != $s1[$i]) continue; for ($j = 0; $j < strlen($s2); $j++) if ($i != $j && $...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Run_BASIC
Run BASIC
' Create string s$ = "Hello, world"   ' String destruction s$ = ""   ' String comparison If s$ = "Hello, world" then print "Equal String"   ' Copying string a$ = s$   ' Check If empty If s$ = "" then print "String is MT"   ' Append a byte s$ = s$ + Chr$(65)   ' Extract a substring a$ = Mid$(s$, 1, 5) '...
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...
#Rust
Rust
use std::str;   fn main() { // Create new string let string = String::from("Hello world!"); println!("{}", string); assert_eq!(string, "Hello world!", "Incorrect string text");   // Create and assign value to string let mut assigned_str = String::new(); assert_eq!(assigned_str, "", "Incorrec...
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 ...
#C.2B.2B
C++
#include <bitset> #include <iostream> #include <limits> #include <string>   void print_bin(unsigned int n) { std::string str = "0";   if (n > 0) { str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string(); str = str.substr(str.find('1')); // remove leading zeros }   std::cout << str <...
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.
#Python
Python
def line(self, x0, y0, x1, y1): "Bresenham's line algorithm" dx = abs(x1 - x0) dy = abs(y1 - y0) x, y = x0, y0 sx = -1 if x0 > x1 else 1 sy = -1 if y0 > y1 else 1 if dx > dy: err = dx / 2.0 while x != x1: self.set(x, y) err -= dy if err < 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
#XSLT
XSLT
<xsl:if test="true() or false()"> True and false are returned by built-in XPath functions. </xsl:if> <xsl:if test="@myAttribute='true'"> Node attributes set to "true" or "false" are just strings. Use string comparison to convert them to booleans. </xsl:if> <xsl:if test="@myAttribute or not($nodeSet)"> Test an att...
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
#Z80_Assembly
Z80 Assembly
BIT 0,A jr nz,true ;;;;;;;;;;;;;;;; AND 1 jr nz,true ;;;;;;;;;;;;;;;; RRCA jr c,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
#zkl
zkl
a:=True; b:=False; True.dir();
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...
#Raku
Raku
sub point (Int $index) { my $ix = $index % 32; if $ix +& 1 { "&point(($ix + 1) +& 28) by &point(((2 - ($ix +& 2)) * 4) + $ix +& 24)" } elsif $ix +& 2 { "&point(($ix + 2) +& 24)-&point(($ix +| 4) +& 28)" } elsif $ix +& 4 { "&point(($ix + 8) +& 16)&point(($ix +| 8) +& 24)" } el...
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 |...
#Lingo
Lingo
put bitAND(2,7) put bitOR(2,7) put bitXOR(2,7) put bitNOT(7)
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...
#PicoLisp
PicoLisp
# Create an empty image of 120 x 90 pixels (setq *Ppm (make (do 90 (link (need 120)))))   # Fill an image with a given color (de ppmFill (Ppm R G B) (for Y Ppm (map '((X) (set X (list R G B))) Y ) ) )   # Set pixel with a color (de ppmSetPixel (Ppm X Y R G B) (set (nth Ppm Y X) (list R G 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...
#PL.2FI
PL/I
  /* Declaration for an image, suitable for BMP files. */ declare image(0:500, 0:500) bit (24) aligned;   image = '000000000000000011111111'b; /* Sets the entire image to red. */   image(10,40) = '111111110000000000000000'b; /* Sets one pixel to blue. */   declare color bit (24) aligned; color = image(20,50); /* ...
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...
#PL.2FI
PL/I
  (fofl, size, subrg): Benford: procedure options(main); /* 20 October 2013 */ declare sc(1000) char(1), f(1000) float (16); declare d fixed (1);   call Fibonacci(f); call digits(sc, f);   put skip list ('digit expected obtained'); do d= 1 upthru 9; put skip edit (d, log10(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...
#PL.2FpgSQL
PL/pgSQL
  WITH recursive constant(val) AS ( SELECT 1000. ) , fib(a,b) AS ( SELECT CAST(0 AS NUMERIC), CAST(1 AS NUMERIC) UNION ALL SELECT b,a+b FROM fib ) , benford(first_digit, probability_real, probability_theoretical) AS ( SELECT *, CAST(log(1. + 1./CAST(first_digit AS INT)) AS NUMERIC(5,4)) probability_theoretical FROM ...
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...
#Perl
Perl
#!perl use strict; use warnings; use List::Util qw(max); use Math::BigRat;   my $one = Math::BigRat->new(1); sub bernoulli_print { my @a; for my $m ( 0 .. 60 ) { push @a, $one / ($m + 1); for my $j ( reverse 1 .. $m ) { # This line: ( $a[$j-1] -= $a[$j] ) *= $j; # is a faster version of the following ...
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...
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make local a: ARRAY [INTEGER] keys: ARRAY [INTEGER] do a := <<0, 1, 4, 5, 6, 7, 8, 9, 12, 26, 45, 67, 78, 90, 98, 123, 211, 234, 456, 769, 865, 2345, 3215, 14345, 24324>> keys := <<0, 42, 45, ...
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...
#Picat
Picat
import cp.   go => Words = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a", "shuffle", "aaaaaaa" ], foreach(Word in Words) best_shuffle(Word,Best,_Score), printf("%s, %s, (%d)\n", Word,Best,diff_word(Word, ...
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...
#Seed7
Seed7
var string: stri is "asdf"; # variable declaration const string: stri is "jkl"; # constant declaration
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...
#Smalltalk
Smalltalk
s := "abc" # create a string (immutable if its a literal constant in the program) s := #[16r01 16r02 16r00 16r03] asString # strings can contain any value, even nulls s := String new:3. # a mutable string v := s # assignment s = t # same contents s < 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 ...
#Ceylon
Ceylon
shared void run() {   void printBinary(Integer integer) => print(Integer.format(integer, 2));   printBinary(5); printBinary(50); printBinary(9k); }
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.
#Racket
Racket
  #lang racket (require racket/draw)   (define (draw-line dc x0 y0 x1 y1) (define dx (abs (- x1 x0))) (define dy (abs (- y1 y0))) (define sx (if (> x0 x1) -1 1)) (define sy (if (> y0 y1) -1 1)) (cond [(> dx dy) (let loop ([x x0] [y y0] [err (/ dx 2.0)]) (unless (= x x1) (send dc draw-...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#zonnon
zonnon
    var a,b,c: boolean; begin a := false; b := true; c := 1 > 2; ...  
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...
#Red
Red
Red []   d: charset [#"N" #"E" #"S" #"W"] ;; main directions hm: #() ;; hm = hashmap - key= heading, value = [box , compass point]   compass-points: [N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE 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 |...
#LiveCode
LiveCode
put "and:" && (255 bitand 2) & comma into bitops put " or:" && (255 bitor 2) & comma after bitops put " xor:" && (255 bitxor 2) & comma after bitops put " not:" && (bitnot 255) after bitops put bitops   -- Ouput and: 2, or: 255, xor: 253, not: 4294967040
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...
#Processing
Processing
PGraphics bitmap = createGraphics(100,100); // Create the bitmap bitmap.beginDraw(); bitmap.background(255, 0, 0); // Fill bitmap with red rgb color bitmap.endDraw(); image(bitmap, 0, 0); // Place bitmap on screen. color b = color(0, 0, 255); // Define a blue rgb color set(50, 50, b); // Set blue colored pixel in the m...
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...
#PowerShell
PowerShell
  $url = "https://oeis.org/A000045/b000045.txt" $file = "$env:TEMP\FibonacciNumbers.txt" (New-Object System.Net.WebClient).DownloadFile($url, $file)   $benford = Get-Content -Path $file | Select-Object -Skip 1 -First 1000 | ForEach-Object {(($_ -split " ")[1].ToString().ToCharArray())[0]} | ...
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...
#Phix
Phix
with javascript_semantics include builtins/mpfr.e procedure bernoulli(mpq rop, integer n) sequence a = mpq_inits(n+1) for m=1 to n+1 do mpq_set_si(a[m], 1, m) for j=m-1 to 1 by -1 do mpq_sub(a[j], a[j+1], a[j]) mpq_set_si(rop, j, 1) mpq_mul(a[j], a[j], rop) ...
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...
#Elixir
Elixir
defmodule Binary do def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)   def search(_tuple, _value, low, high) when high < low, do: :not_found def search(tuple, value, low, high) do mid = div(low + high, 2) midval = elem(tuple, mid) cond do value < midval -> sear...
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...
#PicoLisp
PicoLisp
(de bestShuffle (Str) (let Lst NIL (for C (setq Str (chop Str)) (if (assoc C Lst) (con @ (cons C (cdr @))) (push 'Lst (cons C)) ) ) (setq Lst (apply conc (flip (by length sort Lst)))) (let Res (mapcar '((C) (prog1 (or (find <> Lst...
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...
#PL.2FI
PL/I
shuffle: procedure options (main); /* 14/1/2011 */ declare (s, saves) character (20) varying, c character (1); declare t(length(s)) bit (1); declare (i, k, moves initial (0)) fixed binary;   get edit (s) (L); put skip list (s); saves = s; t = '0'b; do i = 1 to length (s); ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Tcl
Tcl
# string creation set x "hello world"   # string destruction unset x   # string assignment with a null byte set x a\0b string length $x ;# ==> 3   # string comparison if {$x eq "hello"} {puts equal} else {puts "not equal"} set y bc if {$x < $y} {puts "$x is lexicographically less than $y"}   # string copying; cloning h...
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 ...
#Clojure
Clojure
(Integer/toBinaryString 5) (Integer/toBinaryString 50) (Integer/toBinaryString 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.
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @!data;   method fill(Pixel $p) { @!data = $p.clone xx ($!width*$!height) } method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] }   method ...
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...
#REXX
REXX
/*REXX program "boxes the compass" [from degree (º) headings ───► a 32 point set]. */ parse arg $ /*allow º headings to be specified.*/ if $='' then $= 0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25 118.12 118.13 , 135 151.87 151.88 168.75 185.6...
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 |...
#LLVM
LLVM
; ModuleID = 'test.o' ;e means little endian ;p: { pointer size : pointer abi : preferred alignment for pointers } ;i same for integers ;v is for vectors ;f for floats ;a for aggregate types ;s for stack objects ;n: {size:size:size...}, best integer sizes target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:3...
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...
#Prolog
Prolog
  :- module(bitmap, [ new_bitmap/3, fill_bitmap/3, get_pixel0/3, set_pixel0/4 ]).   :- use_module(library(lists)).   %-----------------------------------------------------------------------------% % Convenience Predicates replicate(Term,Times,L):- length(L,Times), maplist(=(Term),L).   replace0(N,OL,E,NL):- nth0...
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...
#Prolog
Prolog
%_________________________________________________________________ % Does the Fibonacci sequence follow Benford's law? %~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ % Fibonacci sequence generator fib(C, [P,S], C, N) :- N is P + S. fib(C, [P,S], Cv, V) :- succ(C, Cn), N is P + S, !, fib(Cn, [S,N], ...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#PicoLisp
PicoLisp
(load "@lib/frac.l")   (de fact (N) (cache '(NIL) N (if (=0 N) 1 (apply * (range 1 N))) ) )   (de binomial (N K) (frac (/ (fact N) (* (fact (- N K)) (fact K)) ) 1 ) )   (de A (N M) (let Sum (0 . 1) (for X M (setq Sum (f+ Sum ...
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...
#Emacs_Lisp
Emacs Lisp
  (defun binary-search (value array) (let ((low 0) (high (1- (length array)))) (cl-do () ((< high low) nil) (let ((middle (floor (+ low high) 2))) (cond ((> (aref array middle) value) (setf high (1- middle))) ((< (aref array middle) value) (setf lo...
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...
#PowerShell
PowerShell
# Calculate best possible shuffle score for a given string # (Split out into separate function so we can use it separately in our output) function Get-BestScore ( [string]$String ) { # Convert to array of characters, group identical characters, # sort by frequecy, get size of first group $MostRepeat...
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...
#VBA
VBA
The Option Compare instruction is used at module level to declare the default comparison method to use when string data is compared. The default text comparison method is Binary.