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/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Racket
Racket
#lang racket   (define current-S-weight (make-parameter 1)) (define current-D-weight (make-parameter 1)) (define current-I-weight (make-parameter 1))   (define bases '(#\A #\C #\G #\T))   (define (fold-sequence seq kons #:finalise (finalise (λ x (apply values x))) . k0s) (define (recur seq . ks) (if (null? seq) ...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Raku
Raku
my @bases = <A C G T>;   # The DNA strand my $dna = @bases.roll(200).join;     # The Task put "ORIGINAL DNA STRAND:"; put pretty $dna; put "\nTotal bases: ", +my $bases = $dna.comb.Bag; put $bases.sort( ~*.key ).join: "\n";   put "\nMUTATED DNA STRAND:"; my $mutate = $dna.&mutate(10); put pretty diff $dna, $mutate; put...
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "msgdigest.s7i"; include "encoding.s7i";   const func boolean: validBitcoinAddress (in string: address) is func result var boolean: isValid is FALSE; local var string: decoded is ""; begin if succeeds(decoded := fromBase58(address)) and length(decoded) = 2...
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#Tcl
Tcl
package require sha256   # Generate a large and boring piece of code to do the decoding of # base58-encoded data. apply {{} { set chars "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" set i -1 foreach c [split $chars ""] { lappend map $c "return -level 0 [incr i]" } lappend map default...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#R
R
  library(png) img <- readPNG("Unfilledcirc.png") M <- img[ , , 1] M <- ifelse(M < 0.5, 0, 1) image(M, col = c(1, 0))   # https://en.wikipedia.org/wiki/Flood_fill floodfill <- function(row, col, tcol, rcol) { if (tcol == rcol) return() if (M[row, col] != tcol) return() M[row, col] <<- rcol floodfill(row - 1, co...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Racket
Racket
  #lang racket   (require racket/draw)   ;; flood-fill: bitmap<%> number number color color -> void ;; An example of flood filling a bitmap. ;; ;; We'll use a raw, byte-oriented interface here for demonstration ;; purposes. Racket does provide get-pixel and set-pixel functions ;; which work on color% structures rather...
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckBoolean { A=True Print Type$(A)="Double" B=1=1 Print Type$(B)="Boolean" Print A=B ' true Print A, B ' -1 True Def boolean C=True, D=False Print C, D , 1>-3 ' True False True K$=Str$(C) Print K$="True" ' True Function ShowBoolean$(&x) ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Maple
Maple
>> islogical(true)   ans =   1   >> islogical(false)   ans =   1   >> islogical(logical(1))   ans =   1   >> islogical(logical(0))   ans =   1   >> islogical(1)   ans =   0   >> islogical(0)   ans =   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...
#JavaScript
JavaScript
function createRow(i, point, heading) { var tr = document.createElement('tr'), td;   td = document.createElement('td'); td.appendChild(document.createTextNode(i)); tr.appendChild(td);   td = document.createElement('td'); point = point.substr(0, 1).toUpperCase() + point.substr(1); td....
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 |...
#Common_Lisp
Common Lisp
(defun bitwise (a b) (print (logand a b)) ; AND (print (logior a b)) ; OR ("ior" = inclusive or) (print (logxor a b)) ; XOR (print (lognot a)) ; NOT (print (ash a b)) ; arithmetic left shift (positive 2nd arg) (print (ash a (- b))) ; arithmetic right shift (negative 2nd arg) ...
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...
#Delphi
Delphi
  program BitmapTest;   {$APPTYPE CONSOLE}   type TColor = record private function GetColor: Cardinal; procedure SetColor(const Value: Cardinal); public Red, Green, Blue, Alpha: Byte; property Color: Cardinal read GetColor write SetColor; end;   TBitmap = class private FPixels: array of ...
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...
#C
C
#include <stdio.h> #include <stdlib.h>   // row starts with 1; col < row size_t bellIndex(int row, int col) { return row * (row - 1) / 2 + col; }   int getBell(int *bellTri, int row, int col) { size_t index = bellIndex(row, col); return bellTri[index]; }   void setBell(int *bellTri, int row, int col, int va...
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...
#AWK
AWK
  # syntax: GAWK -f BENFORDS_LAW.AWK BEGIN { n = 1000 for (i=1; i<=n; i++) { arr[substr(fibonacci(i),1,1)]++ } print("digit expected observed deviation") for (i=1; i<=9; i++) { expected = log10(i+1) - log10(i) actual = arr[i] / n deviation = expected - actual printf...
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...
#ALGOL_68
ALGOL 68
BEGIN # Show Bernoulli numbers B0 to B60 as rational numbers #   # Uses code from the Arithmetic/Rational task modified to use # # LONG LONG INT to allow for the large number of digits requried #   PR precision 100 PR # sets the precision of LONG LONG INT #   # Code from the Arit...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program binSearch64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
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...
#Arturo
Arturo
  count: function [s1 s2][ res: 0 loop.with:'i s1 'c [ if c = s2\[i] -> res: res + 1 ] return res ]   shuff: function [str]-> join shuffle split str   bestShuffle: function [s][ shuffled: shuff s loop 0..dec size shuffled 'i [ if shuffled\[i] <> s\[i] -> continue loo...
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...
#Common_Lisp
Common Lisp
  "string" (coerce '(#\s #\t #\r #\i #\n #\g) 'string)  
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Component_Pascal
Component Pascal
  MODULE NpctBinaryString; IMPORT StdLog,Strings;   PROCEDURE Do*; VAR str: ARRAY 256 OF CHAR; pStr,pAux: POINTER TO ARRAY OF CHAR; b: BYTE; pIni: INTEGER; BEGIN (* String creation, on heap *) NEW(pStr,256); (* Garbage collectable *) NEW(pAux,256);   (* String assingment *) pStr^ := "This is a string on a heap...
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] ...
#Go
Go
package main   import ( "fmt" "sort" )   func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) // uses binary search if index < len(limits) && d == limits[index] { index++ } ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Kotlin
Kotlin
fun printSequence(sequence: String, width: Int = 50) { fun <K, V> printWithLabel(k: K, v: V) { val label = k.toString().padStart(5) println("$label: $v") }   println("SEQUENCE:") sequence.chunked(width).withIndex().forEach { (i, line) -> printWithLabel(i*width + line.length, line...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Lambdatalk
Lambdatalk
  {def DNA CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTT...
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 ...
#8th
8th
  2 base drop #50 . cr  
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.
#Erlang
Erlang
  build_path({Sx, Sy}, {Tx, Ty}) -> if Tx < Sx -> StepX = -1; true -> StepX = 1 end, if Ty < Sy -> StepY = -1; true -> StepY = 1 end,   Dx = abs((Tx-Sx)*2), Dy = abs((Ty-Sy)*2),   if Dy > Dx -> Path = through_y({Sx, Sy}, {Tx, Ty}, {StepX, StepY}, {Dx, Dy}, Dx*2-Dy, []); true -> Pa...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Ring
Ring
  row = 0 dnaList = [] base = ["A","C","G","T"] long = 20 see "Initial sequence:" + nl see " 12345678901234567890" + nl see " " + long + ": "   for nr = 1 to 200 row = row + 1 rnd = random(3)+1 baseStr = base[rnd] see baseStr # + " " if (row%20) = 0 and long < 200 long = long + 20 ...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Ruby
Ruby
class DNA_Seq attr_accessor :seq   def initialize(bases: %i[A C G T] , size: 0) @bases = bases @seq = Array.new(size){ bases.sample } end   def mutate(n = 10) n.times{|n| method([:s, :d, :i].sample).call} end   def to_s(n = 50) just_size = @seq.size / n (0...@seq.size).step(n).map{|fro...
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#UNIX_Shell
UNIX Shell
base58=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z}) bitcoinregex="^[$(printf "%s" "${base58[@]}")]{34}$"   decodeBase58() { local s=$1 for i in {0..57} do s="${s//${base58[i]}/ $i}" done dc <<< "16o0d${s// /+58*}+f" }   checksum() { xxd -p -r <<<"$1" | openssl dgst -sha256 -binary | open...
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#Wren
Wren
import "/crypto" for Sha256 import "/str" for Str import "/fmt" for Conv, Fmt   class Bitcoin { static alphabet_ { "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }   static contentEquals_(ba1, ba2) { if (ba1.count != ba2.count) return false return !(0...ba1.count).any { |i| ba1[i] ...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Raku
Raku
class Pixel { has Int ($.R, $.G, $.B) } class Bitmap { has Int ($.width, $.height); has Pixel @.data;   method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] } }   role PPM { method P6 returns Blob { "P6\n{self.width} {self.height}\n255\n...
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
>> islogical(true)   ans =   1   >> islogical(false)   ans =   1   >> islogical(logical(1))   ans =   1   >> islogical(logical(0))   ans =   1   >> islogical(1)   ans =   0   >> islogical(0)   ans =   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
#MATLAB
MATLAB
>> islogical(true)   ans =   1   >> islogical(false)   ans =   1   >> islogical(logical(1))   ans =   1   >> islogical(logical(0))   ans =   1   >> islogical(1)   ans =   0   >> islogical(0)   ans =   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...
#Julia
Julia
using Printf   function degree2compasspoint(d::Float64) majors = ("north", "east", "south", "west", "north", "east", "south", "west") quarter1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N") quarter2 = map(p -> replace(p, "NE" => "EN"), quarter1)   d = d % 360 + 360 / 64 imaj...
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 |...
#D
D
T rot(T)(in T x, in int shift) pure nothrow @nogc { return (x >>> shift) | (x << (T.sizeof * 8 - shift)); }   void testBit(in int a, in int b) { import std.stdio; writefln("Input: a = %d, b = %d", a, b); writefln("AND  : %8b & %08b = %032b (%4d)", a, b, a & b, a & b); writefln(" OR  : %8b | %08b = %032b (...
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...
#E
E
def makeFlexList := <elib:tables.makeFlexList> def format := <import:java.lang.makeString>.format   def CHANNELS := 3 def UByte := 0..255   def makeColor { to fromFloat(r, g, b) { return makeColor.fromByte((r * 255).round(), (g * 255).round(), (b * 255)....
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#C.23
C#
using System; using System.Numerics;   namespace BellNumbers { public static class Utility { public static void Init<T>(this T[] array, T value) { if (null == array) return; for (int i = 0; i < array.Length; ++i) { array[i] = value; } } }   ...
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...
#BCPL
BCPL
  GET "libhdr"   MANIFEST { fib_sz = 1_000_000_000 // keep 9 significant digits for computing F(n) }   LET msd(n) = VALOF { UNTIL n < 10 DO n /:= 10 RESULTIS n }   LET fibonacci(n, tally) BE { LET a, b, c, e = 0, 1, ?, 0 FOR i = 1 TO n { TEST e = 0 THEN tally[msd(b)] +:= 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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h>   float *benford_distribution(void) { static float prob[9]; for (int i = 1; i < 10; i++) prob[i - 1] = log10f(1 + 1.0 / i);   return prob; }   float *get_actual_distribution(char *fn) { FILE *input = fopen(fn, "r"); if (!input) { ...
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...
#Bracmat
Bracmat
( BernoulliList = B Bs answer indLn indexLen indexPadding , n numberPadding p solPos solidusPos sp . ( B = m A a j b . -1:?m & :?A & whl ' ( 1+!m:~>!arg:?m & ((!m+1:?j)^-1:?a) map ...
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...
#ACL2
ACL2
(defun defarray (name size initial-element) (cons name (compress1 name (cons (list :HEADER :DIMENSIONS (list size) :MAXIMUM-LENGTH (1+ size) :DEFAULT initial-element ...
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...
#AutoHotkey
AutoHotkey
words := "abracadabra,seesaw,elk,grrrrrr,up,a" Loop Parse, Words,`, out .= Score(A_LoopField, Shuffle(A_LoopField)) MsgBox % clipboard := out     Shuffle(String) { Cord := String Length := StrLen(String) CharType := A_IsUnicode ? "UShort" : "UChar"   Loop, Parse, String ; For each old character in String... { ...
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#D
D
void main() /*@safe*/ { import std.array: empty, replace; import std.string: representation, assumeUTF;   // String creation (destruction is usually handled by // the garbage collector). ubyte[] str1;   // String assignments. str1 = "blah".dup.representation; // Hex string, same as "\x00...
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] ...
#Haskell
Haskell
import Control.Monad (foldM) import Data.List (partition)   binSplit :: Ord a => [a] -> [a] -> [[a]] binSplit lims ns = counts ++ [rest] where (counts, rest) = foldM split ns lims split l i = let (a, b) = partition (< i) l in ([a], b)   binCounts :: Ord a => [a] -> [a] -> [Int] binCounts b = fmap length . bi...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Lua
Lua
function prettyprint(seq) -- approx DDBJ format seq = seq:gsub("%A",""):lower() local sums, n = { a=0, c=0, g=0, t=0 }, 1 seq:gsub("(%a)", function(c) sums[c]=sums[c]+1 end) local function printf(s,...) io.write(s:format(...)) end printf("LOCUS AB000000  %12d bp mRNA linear HUM 01-JAN-2001\n"...
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 ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program binarydigit.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
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.
#ERRE
ERRE
  PROGRAM BRESENHAM   !$INCLUDE="PC.LIB"   PROCEDURE BRESENHAM ! === Draw a line using graphic coordinates ! Inputs are X1, Y1, X2, Y2: Destroys value of X1, Y1 dx=ABS(x2-x1) sx=-1 IF x1<x2 THEN sx=1 dy=ABS(y2-y1) sy=-1 IF y1<y2 THEN sy=1 er=-dy IF dx>dy THEN er=dx er=INT(er/2) LOOP PSET(x1,y1,1) EXIT IF x1=x2 AN...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Swift
Swift
let bases: [Character] = ["A", "C", "G", "T"]   enum Action: CaseIterable { case swap, delete, insert }   @discardableResult func mutate(dna: inout String) -> Action { guard let i = dna.indices.shuffled().first(where: { $0 != dna.endIndex }) else { fatalError() }   let action = Action.allCases.randomElement...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Vlang
Vlang
import rand import rand.seed   const bases = "ACGT"   // 'w' contains the weights out of 300 for each // of swap, delete or insert in that order. fn mutate(dna string, w [3]int) string { le := dna.len // get a random position in the dna to mutate p := rand.intn(le) or {0} // get a random number between ...
http://rosettacode.org/wiki/Bitcoin/address_validation
Bitcoin/address validation
Bitcoin/address validation You are encouraged to solve this task according to the task description, using any language you may know. Task Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of th...
#zkl
zkl
var [const] MsgHash=Import("zklMsgHash"); // SHA-256, etc const symbols="123456789" // 58 characters: no cap i,o; ell, zero "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz";   fcn unbase58(str){ // --> Data (byte bucket) out:=Data().fill(0,25); str.pump(Void,symbols.index,'wrap(n){ // throw...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#REXX
REXX
/*REXX program demonstrates a method to perform a flood fill of an area. */ black= '000000000000000000000000'b /*define the black color (using bits).*/ red = '000000000000000011111111'b /* " " red " " " */ green= '000000001111111100000000'b ...
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Maxima
Maxima
is(1 < 2); /* true */   is(2 < 1); /* false */   not true; /* false */   not false; /* true */
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Metafont
Metafont
boolTrue = true boolFalse = false   if boolTrue then print "boolTrue is true, and its value is: " + boolTrue   if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse   mostlyTrue = 0.8 kindaTrue = 0.4 print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue) print "mostlyTrue OR kinda...
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
#min
min
boolTrue = true boolFalse = false   if boolTrue then print "boolTrue is true, and its value is: " + boolTrue   if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse   mostlyTrue = 0.8 kindaTrue = 0.4 print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue) print "mostlyTrue OR kinda...
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...
#K
K
d:("N;Nbe;N-ne;Nebn;Ne;Nebe;E-ne;Ebn;") d,:("E;Ebs;E-se;Sebe;Se;Sebs;S-se;Sbe;") d,:("S;Sbw;S-sw;Swbs;Sw;Swbw;W-sw;Wbs;") d,:("W;Wbn;W-nw;Nwbw;Nw;Nwbn;N-nw;Nbw;N")   split:{1_'(&x=y)_ x:y,x} dd:split[d;";"]   / lookup table s1:"NEWSnewsb-" s2:("North";"East";"West";"South";"north";"east";"wes...
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 |...
#Delphi
Delphi
program Bitwise;   {$APPTYPE CONSOLE}   begin Writeln('2 and 3 = ', 2 and 3); Writeln('2 or 3 = ', 2 or 3); Writeln('2 xor 3 = ', 2 xor 3); Writeln('not 2 = ', not 2); Writeln('2 shl 3 = ', 2 shl 3); Writeln('2 shr 3 = ', 2 shr 3); // there are no built-in rotation operators in Delphi Readln; end.
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#EchoLisp
EchoLisp
  (lib 'plot) (define width 600) (define height 400)   (plot-size width height) ;; set image size   (define (blue x y) (rgb 0.0 0.0 1.0)) ;; a constant function (plot-rgb blue 1 1) ;; blue everywhere   (lib 'types) ;; uint32 and uint8 vector types   ;; bit-map pixel access (define bitmap (pixels->uint32-vector)) ;; scr...
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...
#C.2B.2B
C++
#include <iostream> #include <vector>   #ifdef HAVE_BOOST #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; #else typedef unsigned int integer; #endif   auto make_bell_triangle(int n) { std::vector<std::vector<integer>> bell(n); for (int i = 0; i < n; ++i) bell[...
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...
#C.2B.2B
C++
//to cope with the big numbers , I used the Class Library for Numbers( CLN ) //if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram" #include <cln/integer.h> #include <cln/integer_io.h> #include <iostream> #include <algorithm> #include <vector> #include <iomanip> #include <s...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#C
C
  #include <stdlib.h> #include <gmp.h>   #define mpq_for(buf, op, n)\ do {\ size_t i;\ for (i = 0; i < (n); ++i)\ mpq_##op(buf[i]);\ } while (0)   void bernoulli(mpq_t rop, unsigned int n) { unsigned int m, j; mpq_t *a = malloc(sizeof(mpq_t) * (n + 1)); mpq_for(a, init, 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...
#Action.21
Action!
INT FUNC BinarySearch(INT ARRAY a INT len,value) INT low,high,mid   low=0 high=len-1 WHILE low<=high DO mid=low+(high-low) RSH 1 IF a(mid)>value THEN high=mid-1 ELSEIF a(mid)<value THEN low=mid+1 ELSE RETURN (mid) FI OD RETURN (-1)   PROC Test(INT ARRAY a INT len,value) ...
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...
#AWK
AWK
{ scram = best_shuffle($0) print $0 " -> " scram " (" unchanged($0, scram) ")" }   function best_shuffle(s, c, i, j, len, r, t) { len = split(s, t, "")   # Swap elements of t[] to get a best shuffle. for (i = 1; i <= len; i++) { for (j = 1; j <= len; j++) { # Swap t[i] and t[j] if they will not match # ...
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :b make-blob 10 #ten bytes of initial size set-to b 0 255 !. get-from b 0 #prints 255 !. b #prints (blob:ff000000000000000000) local :b2 make-blob 3 set-to b2 0 97 set-to b2 1 98 set-to b2 2 99 !. b #prints (blob:"abc") !. !encode!utf-8 b #prints "abc"  
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...
#Delphi
Delphi
  program Binary_strings;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var x : string; c : TArray<Byte>; objecty, y : string; empty : string; nullString : string; whitespace, slice, greeting, join : string; begin //string creation x:= String....
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] ...
#J
J
Idotr=: |.@[ (#@[ - I.) ] NB. reverses order of limits to obtain intervals closed on left, open on right (>= y <) binnedData=: adverb define bidx=. i.@>:@# x NB. indicies of bins x (Idotr (u@}./.)&(bidx&,) ]) y NB. apply u to data in each bin after dropping first value )   require...
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] ...
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.List;   public class Bins { public static <T extends Comparable<? super T>> int[] bins( List<? extends T> limits, Iterable<? extends T> data) { int[] result = new int[limits.size() + 1]; for (T n : data) { ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
seq = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCA\ ATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGC\ AATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGA\ TTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTC\ TTTTAGTACGTCGGGAGTGGTATTATATTTAA...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#MATLAB_.2F_Octave
MATLAB / Octave
  function r = base_count(f) fid = fopen(f,'r'); nn=[0,0,0,0]; while ~feof(fid) s = fgetl(fid); fprintf(1,'%5d :%s\n', sum(nn), s(s=='A'|s=='C'|s=='G'|s=='T')); nn = nn+[sum(s=='A'),sum(s=='C'),sum(s=='G'),sum(s=='T')]; end fclose(fid);   fprintf(1, '\nBases:\n\n A  : %d\n C  : %d\n G...
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 ...
#ACL2
ACL2
(include-book "arithmetic-3/top" :dir :system)   (defun bin-string-r (x) (if (zp x) "" (string-append (bin-string-r (floor x 2)) (if (= 1 (mod x 2)) "1" "0"))))   (defun bin-string (x) (if (zp x) "0" (bin-string-r x)))
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.
#Euphoria
Euphoria
include std/console.e include std/graphics.e include std/math.e   -- the new_image function and related code in the 25 or so -- lines below are from http://rosettacode.org/wiki/Basic_bitmap_storage#Euphoria -- as of friday, march 2, 2012   -- Some color constants: constant black = #000000, white = #FFFFFF, ...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt import "/sort" for Sort   var rand = Random.new() var bases = "ACGT"   // 'w' contains the weights out of 300 for each // of swap, delete or insert in that order. var mutate = Fn.new { |dna, w| var le = dna.count // get a random position in the dna to mutate ...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Ruby
Ruby
# frozen_string_literal: true   require_relative 'raster_graphics'   class RGBColour def ==(other) values == other.values end end   class Pixmap def flood_fill(pixel, new_colour) current_colour = self[pixel.x, pixel.y] queue = Queue.new queue.enq(pixel) until queue.empty? p = queue.pop ...
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
#MiniScript
MiniScript
boolTrue = true boolFalse = false   if boolTrue then print "boolTrue is true, and its value is: " + boolTrue   if not boolFalse then print "boolFalse is not true, and its value is: " + boolFalse   mostlyTrue = 0.8 kindaTrue = 0.4 print "mostlyTrue AND kindaTrue: " + (mostlyTrue and kindaTrue) print "mostlyTrue OR kinda...
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
#Mirah
Mirah
import java.util.ArrayList import java.util.HashMap   # booleans puts 'true is true' if true puts 'false is false' if (!false)   # lists treated as booleans x = ArrayList.new puts "empty array is true" if x x.add("an element") puts "full array is true" if x puts "isEmpty() is false" if !x.isEmpty()   # maps treated as...
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
#Modula-2
Modula-2
MODULE boo;   IMPORT InOut;   VAR result, done : BOOLEAN; A, B : INTEGER;   BEGIN result := (1 = 2); result := NOT result; done := FALSE; REPEAT InOut.ReadInt (A); InOut.ReadInt (B); done := A > B UNTIL done END boo.
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...
#Kotlin
Kotlin
// version 1.1.2   fun expand(cp: String): String { val sb = StringBuilder() for (c in cp) { sb.append(when (c) { 'N' -> "north" 'E' -> "east" 'S' -> "south" 'W' -> "west" 'b' -> " by " else -> "-" }) } return ...
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 |...
#DWScript
DWScript
PrintLn('2 and 3 = '+IntToStr(2 and 3)); PrintLn('2 or 3 = '+IntToStr(2 or 3)); PrintLn('2 xor 3 = '+IntToStr(2 xor 3)); PrintLn('not 2 = '+IntToStr(not 2)); PrintLn('2 shl 3 = '+IntToStr(2 shl 3)); PrintLn('2 shr 3 = '+IntToStr(2 shr 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...
#Elixir
Elixir
  defmodule RosBitmap do defrecord Bitmap, pixels: nil, shape: {0, 0}   defp new(width, height, {:rgb, r, g, b}) do Bitmap[ pixels: :array.new(width * height, {:default, <<r::size(8), g::size(8), b::size(8)>>}), shape: {width, height}] end   def new(width, height), do: new(width, height,...
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...
#CLU
CLU
bell = cluster is make, get rep = array[int]   idx = proc (row, col: int) returns (int) return (row * (row - 1) / 2 + col) end idx   get = proc (tri: cvt, row, col: int) returns (int) return (tri[idx(row, col)]) end get   make = proc (rows: int) returns (cvt) length: int ...
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...
#Common_Lisp
Common Lisp
;; The triangle is a list of arrays; each array is a ;; triangle's row; the last row is at the head of the list. (defun grow-triangle (triangle) (if (null triangle) '(#(1)) (let* ((last-array (car triangle)) (last-length (length last-array)) (new-array (make-array (1+ last-l...
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...
#Clojure
Clojure
(ns example (:gen-class))   (defn abs [x] (if (> x 0) x (- x)))   (defn calc-benford-stats [digits] " Frequencies of digits in data " (let [y (frequencies digits) tot (reduce + (vals y))] [y tot]))   (defn show-benford-stats [v] " Prints in percent the actual, Benford expected, and differ...
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#C.23
C#
  using Mpir.NET; using System;   namespace Bernoulli { class Program { private static void bernoulli(mpq_t rop, uint n) { mpq_t[] a = new mpq_t[n + 1];   for (uint i = 0; i < n + 1; i++) { a[i] = new mpq_t(); }   for (u...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Recursive_Binary_Search is Not_Found : exception;   generic type Index is range <>; type Element is private; type Array_Of_Elements is array (Index range <>) of Element; with function "<" (L, R : Element) return Boolean is <>; functio...
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...
#BaCon
BaCon
DECLARE case$[] = { "tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a" }   FOR z = 0 TO UBOUND(case$)-1   result$ = EXPLODE$(case$[z], 1) FOR y = 1 TO AMOUNT(result$) FOR x = 1 TO LEN(case$[z]) IF TOKEN$(result$, y) <> MID$(case$[z], x, 1) AND TOKEN$(result$, x) = MID$(case$[z], x,...
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...
#E
E
? def int8 := <type:java.lang.Byte> # value: int8
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...
#Elixir
Elixir
# String creation x = "hello world"   # String destruction x = nil   # String assignment with a null byte x = "a\0b" IO.inspect x #=> <<97, 0, 98>> IO.puts String.length(x) #=> 3   # string comparison if x == "hello" do IO.puts "equal" else IO.puts "not equal" #=> not equal end y = "bc...
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] ...
#jq
jq
# input and output: {limits, count} where # .limits holds an array defining the limits, and # .count[$i] holds the count of bin $i, where bin[0] is the left-most bin def bin($x): (.limits | bsearch($x)) as $ix | (if $ix > -1 then $ix + 1 else -1 - $ix end) as $i | .count[$i] += 1;   # pretty-print for the s...
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] ...
#Julia
Julia
"""Add the function Python has in its bisect library""" function bisect_right(array, x, low = 1, high = length(array) + 1) while low < high middle = (low + high) ÷ 2 x < array[middle] ? (high = middle) : (low = middle + 1) end return low end   """ Bin data according to (ascending) limits """...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Nim
Nim
import strformat import strutils   const Source = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" & "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" & "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" & "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" & ...
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Pascal
Pascal
program DNA_Base_Count; {$IFDEF FPC} {$MODE DELPHI}//String = AnsiString {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} const dna = 'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG' + 'CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' + 'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT' + ...
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 ...
#Action.21
Action!
PROC PrintBinary(CARD v) CHAR ARRAY a(16) BYTE i=[0]   DO a(i)=(v&1)+'0 i==+1 v=v RSH 1 UNTIL v=0 OD   DO i==-1 Put(a(i)) UNTIL i=0 OD RETURN   PROC Main() CARD ARRAY data=[0 5 50 9000] BYTE i CARD v   FOR i=0 TO 3 DO v=data(i) PrintF("Output for %I is ",v) Pr...
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.
#F.23
F#
let inline bresenham fill (x0, y0) (x1, y1) = let steep = abs(y1 - y0) > abs(x1 - x0) let x0, y0, x1, y1 = if steep then y0, x0, y1, x1 else x0, y0, x1, y1 let x0, y0, x1, y1 = if x0 > x1 then x1, y1, x0, y0 else x0, y0, x1, y1 let dx, dy = x1 - x0, abs(y1 - y0) let s = if y0 < y1 then 1 else -1 let...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#zkl
zkl
var [const] bases="ACGT", lbases=bases.toLower(); dna:=(190).pump(Data().howza(3),(0).random.fp(0,4),bases.get); // bucket of bytes   foreach s,m in (T("Original","Mutated").zip(T(True,False))){ println("\n",s," DNA strand:"); dnaPP(dna); println("Base Counts: ", dna.len()," : ", dna.text.toUpper().counts()...
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Rust
Rust
  use rand::prelude::*; use std::collections::HashMap; use std::fmt::{Display, Formatter, Error};   pub struct Seq<'a> { alphabet: Vec<&'a str>, distr: rand::distributions::Uniform<usize>, pos_distr: rand::distributions::Uniform<usize>, seq: Vec<&'a str>, }   impl Display for Seq<'_> { fn fmt(&self,...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Rust
Rust
  /* Naive Rust implementation of RosettaCode's Bitmap/Flood fill excercise. * * For the sake of simplicity this code reads PPM files (format specification can be found here: http://netpbm.sourceforge.net/doc/ppm.html ). * The program assumes that the image has been created by GIMP in PPM ASCII mode and panics at an...
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Scala
Scala
import java.awt.Color import scala.collection.mutable   object Flood { def floodFillStack(bm:RgbBitmap, x: Int, y: Int, targetColor: Color): Unit = { // validate if (bm.getPixel(x,y) == targetColor) return   // vars val oldColor = bm.getPixel(x,y) val pixels = new mutable.Stack[(Int,Int)]   //...
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
#Modula-3
Modula-3
TYPE BOOLEAN = {FALSE, TRUE}
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Monte
Monte
  def example(input :boolean): if input: return "Input was true!" return "Input was 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
#MUMPS
MUMPS
a = true b = false   if a println "a is true" else if b println "b is true" end
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...
#langur
langur
val .box = ["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 we...
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 |...
#E
E
def bitwise(a :int, b :int) { println(`Bitwise operations: a AND b: ${a & b} a OR b: ${a | b} a XOR b: ${a ^ b} NOT a: " + ${~a} a left shift b: ${a << b} a right shift b: ${a >> 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...
#Erlang
Erlang
  -module(ros_bitmap).   -export([new/2, fill/2, set_pixel/3, get_pixel/2]).   -record(bitmap, { pixels = nil, shape = {0, 0} }).   new(Width, Height) -> #bitmap{pixels=array:new(Width * Height, {default, <<0:8, 0:8, 0:8>>}), shape={Width, Height}}.   fill(#bitmap{shape={Width, Height}}, {rgb, R, G, B}) -> ...
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Cowgol
Cowgol
include "cowgol.coh";   typedef B is uint32; typedef I is intptr;   sub bellIndex(row: I, col: I): (addr: I) is addr := (row * (row - 1) / 2 + col) * @bytesof B; end sub;   sub getBell(row: I, col: I): (bell: B) is bell := [LOMEM as [B] + bellIndex(row, col)]; end sub;   sub setBell(row: I, col: I, bell: B) is ...